c++ - 如何在 While 循环中打印出矩阵格式的二维数组
问题描述
我有一个很大的 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循环中,(在文本文件中使用完全相同的整数),它只会输出一堆随机值......</p>
解决方案
这是一个示例,我测试了以下代码以打印矩阵格式的二维数组。您可以使用 printf("%5d"....) 代替 cout。%[n]d,其中 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.
推荐阅读
- python - Chart.js 尝试渲染图表时遇到多个错误
- c - LDR Rd,-Label 与 LDR Rd,[PC+Offset]
- html - 我需要获取 Shopify 网站的商店详细信息
- mysql - laravel 与 json 列的关系
- python - 查找给定列中单词列表的总出现次数(SQL/Pandas DataFrame)
- c# - 传送错误 Unity 2d
- javascript - “HTMLElement”类型上不存在属性“r”
- google-apps-script - 使用工作表而不是电子表格的基于函数的触发器失败
- php - 客户端错误:`POST http://localhost//oauth/token` 导致 `404 Not Found` 响应:
- plm - N = 2 和 T = 60 个四分之一的面板的标准误差 - 使用哪些稳健的标准误差 - vcovHC 或 vcovBK?