首页 > 解决方案 > 二维数组中的用户输入 (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;
}

标签: c++for-loopuser-inputnested-loops

解决方案


#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;
}

推荐阅读