二维数组中的用户输入 (C++) [英] User input in 2D array (C++)
本文介绍了二维数组中的用户输入 (C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不确定为什么当我打印检查时 for 循环不会在二维数组中保存正确的值.有什么想法吗?
Not sure why the for loop won't save the correct values in the 2D array when I printed to check. Any ideas?
#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;
}
这篇关于二维数组中的用户输入 (C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文