【问题标题】:Creating a 2D array with user input [closed]使用用户输入创建二维数组 [关闭]
【发布时间】:2022-01-10 19:38:02
【问题描述】:

我正在尝试制作一个二维数组,用户可以在其中输入数组可以采用的元素数量,以及数组中的元素。我想我设法创建了数组,但是当我尝试将一些元素放入其中时,例如 2x2 数组并将 2 作为其所有元素,我将其命名为 output。代码如下:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int rowCount,colCount;
    cout<<"Enter the number of rows in Grid-Land:";
    cin>>rowCount;
    cout<<"Enter the number of columns in Grid-Land:";
    cin>>colCount;
    int** arr = new int*[rowCount];
    for(int i = 0; i < rowCount; ++i)
        arr[i] = new int[colCount];
    cout<<"Enter the garbage amounts at the nodes of the MxN Grid-Land:"<<endl;     //Elements of the array
    for(int i=0; i<rowCount; i++){
        for (int j=0; i<colCount; i++)
            cin>>arr[i][j];
    }   
    cout<<"\nThe 2-D Array is:\n";
    for(int i=0;i<rowCount;i++){
        for(int j=0;j<colCount;j++){
            cout<<"\t"<<arr[i][j];
        }
        cout<<endl;
      } 
    return 0;
}

【问题讨论】:

  • for (int j=0; i&lt;colCount; i++)你不是说for (int j=0; j&lt;colCount; j++)吗?
  • 查看您的 for 循环。继续看他们,直到你看到你的错字。
  • new,但没有delete。闻起来像内存泄漏
  • 就像@kmoser 提到的,内部循环显然是这里的根本原因

标签: c++ arrays


【解决方案1】:

这是一个错字。在获取输入时,您没有在内部循环中使用“j”变量,而是使用了“i”变量。

【讨论】:

    【解决方案2】:

    您在提示用户输入数组值的 for 循环中出现拼写错误。您将 j 切换为 i,因此您实际上只迭代一列,而不会提示用户输入其余值。

    改变这个

    for(int i=0; i<rowCount; i++){
            for (int j=0; i<colCount; i++)
                cin>>arr[i][j];
        }
    }
    

    为此

    for(int i=0; i<rowCount; i++){
            for (int j=0; j<colCount; j++)
                cin>>arr[i][j];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2021-12-07
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多