繁体   English   中英

二维数组的 scanf 和行读取

[英]scanf and line reading for 2d array

尽管关于 scanf 和行输入读取的主题很少,但我想知道我的代码片段为什么在 2D 数组上使用它不起作用,即使程序正确结束,它也是一个无限循环吗? 因为它没有给出错误,也没有在输出上打印一些东西,如果有人能告诉我出了什么问题?

using namespace std;

int main() {

    int t, j = 0;
    cin >> t;
    int arr2d[t][t];
    while (t--) {
        for (int i=0; i <= t; i++) {
            while (scanf("%d", &arr2d[i][j])) {
                cout << arr2d[i][j];
                j++;
            }
        }
    }
    return 0;
}

输入为:

3
1 1 0
1 1 1
1 0 0

谢谢你!

这是读取矩阵的一种方法:

unsigned int capacity = 0u;
std::cin >> capacity;
std::vector<int> matrix(capacity * capacity);
for (int row = 0; row < capacity; ++row)
{
    for (int column = 0; column < capacity; ++column)
    {
        int number;
        std::cin >> number;
        matrix[row * capacity + column] = number;
    }
    std::cin.ignore(10000, '\n'); // Reset to next line.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM