且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在While循环中以矩阵格式打印二维数组

更新时间:2022-12-06 23:26:12

这是一个示例,我测试了下面的代码以矩阵格式打印2D数组.您可以使用printf(%5d" ....)代替cout.%[n] d,其中n是相加那么多空格的整数.

This is an example, I tested the below code for printing a 2D array in matrix format. You can use printf("%5d"....) instead of cout. %[n]d, where n is the integer adding that many spaces.

while (!inFile.eof())
{
    bad = false;
    for (int i = 0; (i < MAX_ROWS) && !bad; i++) {
        for (int j = 0; (j < MAX_COLUMNS) && !bad; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "\nThe array does not have enough integers\n";
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            if (!bad) {
                printf("%3d",ArrB[i][j]);
                //cout << *(*(ArrB + i) + j) << " ";
            }
        }
        printf("\n");
    }

输出:

  1  2
  3  4
  5  6

 The size of the array is correct.
  1  2
  3  7
  5  8

 The size of the array is correct.
 -5  9
  4
 The array does not have enough integers


 There is/are negative number(s) or zero(s) in the array imported from 
 your text file.