c++ - 二维数组中的用户输入 (C++)
问题描述
不知道为什么当我打印检查时 for 循环不会在二维数组中保存正确的值。有任何想法吗?
#include <iostream>
using namespace std;
int row, col;
int main()
{
int num;
int val[row][col];
cout << "How many rows are there?" << endl;
cin >> row;
cout << "How many columns are there?" << endl;
cin >> col;
cout << "Enter values for the matrix: " << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> val[i][j];
}
}
return 0;
}
解决方案
#include <iostream>
using namespace std;
int main()
{
int row, col;
cout << "How many rows are there?" << endl;
cin >> row;
cout << "How many columns are there?" << endl;
cin >> col;
cout << "Enter values for the matrix: " << endl;
// check if row and col > 0
int* val = new int[row * col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> val[i * col + j];
}
}
delete[] val;
return 0;
}
推荐阅读
- swift - 创建 ML 文本分类器概率
- c# - 仅在经过一些操作后,如何将值传递给 C# 中的基本构造函数
- ios - 如何在运行时从 SpriteKit 中的 plist 创建 SKTextureAtlas?
- draftjs - Draft.js 在两个编辑器之间复制时的文本内联样式
- azure - 使用查询创建 Azure 警报以监视多个 VM?
- vaadin - 如何在 Vaadin 10 中找出按钮的宽度?
- android - get(position) 在空引用上显示
- javascript - ThreeJS:如何弯曲二维形状?
- ubuntu - 升级到 ubuntu 18 后通过 Putty 和 RDP 失去所有连接
- javascript - webgl bufferdata 和 enableVertexAttribute 函数需要很多时间