我有一个很大的while循环,它将整数从文本文件读取到二维数组中,并计算数组的长度。这个循环运行得非常好。
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "inFilePgm2A.txt";
ifstream inFile;
inFile.open(fileName);
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
bool bad = false;
bool invalidnum = false;
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) {
cout << *(*(ArrB + i) + j) << " ";
}
}
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
}
return 0;
}例如,如果我的文本文件包含以下整数:
1 2 3 4 5 6 -1 1 2 3 7 5 8 -1 -5 9 4 -1
这将是结果:

问题是,当数组在while循环中时,我不知道如何打印矩阵格式的二维数组。
因此,我希望它显示为“1 2 3 4 5 6”
1 2
3 4
5 6
数组的大小是正确的…。
通常,我可以使用下面的代码打印矩阵格式的数组
for(int i = 0; i < MAX_ROWS; i++)
{
for(int j = 0; j < MAX_COLUMNS; j++)
{
cout<<ArrB[i][j]<<"\t";
}
cout<<endl;
}但是这段代码在while循环中不起作用,如果我将上面的代码放在while循环中(在文本文件中使用完全相同的整数),它将只输出一堆随机值…

发布于 2020-02-28 23:24:26
这是一个例子,我测试了以下打印矩阵格式的二维数组的代码。您可以使用printf("%5d"....)而不是cout。%nd,其中n是加上那么多空格的整数。
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.https://stackoverflow.com/questions/60454533
复制相似问题