c++ - 我想在 C++ 中显示二维数组的所有条目

标签 c++

我想创建一个程序,从用户那里获取二维数组的行和列的大小,然后从用户那里获取数组的所有条目。最后显示从 array[0][0] 到 array[size][size] 的所有条目。

我的代码是:

#include <iostream>
using namespace std;

int main()
{
    int rows, columns;
    int tom[rows][columns];
    cout << "Size of array rows: ";
    cin >> rows;
    cout << "Size of array columns: ";
    cin >> columns;

    for(int count1 = 0; count1 < rows; count1++)
    {
        for(int count2 = 0; count2 < columns; count2++)
        {
            cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
            cin >> tom[count1][count2];
        }
    }
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < columns; j++)
        {
            cout << tom[i][j] << endl;
        }
    }
    return 0;
}

输出是:

Size of array rows: 2
Size of array columns: 3
Enter entry of row 0 and column 0: 1
Enter entry of row 0 and column 1: 2
Enter entry of row 0 and column 2: 3
Enter entry of row 1 and column 0: 12
Enter entry of row 1 and column 1: 13
Enter entry of row 1 and column 2: 14
12
13
14
12
13
14

它应该给出输出:

1
2
3
12
13
14

问题是什么? 请帮忙。

最佳答案

你不能像这样动态地创建一个数组。这甚至不应该编译。即使是这样,您也是在 让用户输入维度之前创建数组。对于正确的方法使用 std::vector :

#include <iostream>
#include <vector>

int main()
{
    int rows, columns;
    std::cout << "Size of array rows: ";
    std::cin >> rows;
    std::cout << "Size of array columns: ";
    std::cin >> columns;
    std::vector<std::vector<int>> tom(rows, std::vector<int>(columns));

    for (int count1 = 0; count1 < rows; count1++)
    {
        for (int count2 = 0; count2 < columns; count2++)
        {
            std::cout << "Enter entry of row " << count1 << " and column " << count2 << ": ";
            std::cin >> tom[count1][count2];
        }
    }
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            std::cout << tom[i][j] << std::endl;
        }
    }
    return 0;
}

输出:

Size of array rows: 2
Size of array columns: 3
Enter entry of row 0 and column 0: 1
Enter entry of row 0 and column 1: 2
Enter entry of row 0 and column 2: 3
Enter entry of row 1 and column 0: 12
Enter entry of row 1 and column 1: 13
Enter entry of row 1 and column 2: 14
1
2
3
12
13
14

请不要使用 using namespace std; - 阅读 here为什么。

关于c++ - 我想在 C++ 中显示二维数组的所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54443395/

相关文章:

c++ - 从 C 文件调用 C++ 函数会出现 "undefined reference"编译器错误

c++ - 将参数传递给 C++ 构造函数时 VS 编译错误

c++ - 指向不完整类型数据成员的指针

C++ Friend 方法无法从类访问私有(private)数据

c++ - 寻找最近的较小素数的快速算法

c++ - 如何使用 sizeof(a)/sizeof(a[n])

c++ - C++中Variadic templates类的Variadic templates

c++ - 可以用 std::for_each 改变对象吗?

c++ - C++中的前缀递归表示法

c++ - 了解函数是否在运行时获取引用或值