我正在开发一个用文本文件中的数据填充数组的程序。当我输出数组时,它的内容与我认为的顺序不符。我认为问题出在将数据输入数组或将数组输出到 iostream 的 for 循环之一。谁能发现我的错误?
数据:
(我将每行的第一个数字更改为 2-31,以区别于 0 和 1)
输出:
代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream inFile;
int FC_Row, FC_Col, EconRow, EconCol, seat, a, b;
inFile.open("Airplane.txt");
inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;
int airplane[100][6];
int CurRow = 0;
int CurCol = 0;
while ( (inFile >> seat) && (CurRow < FC_Row))
{
airplane[CurRow][CurCol] = seat;
++CurCol;
if (CurCol == FC_Col)
{
++CurRow;
CurCol = 0;
}
}
while ( (inFile >> seat) && (CurRow < EconRow))
{
airplane[CurRow][CurCol] = seat;
++CurCol;
if (CurCol == EconCol)
{
++CurRow;
CurCol = 0;
}
}
cout << setw(11)<< "A" << setw(6) << "B"
<< setw(6) << "C" << setw(6) << "D"
<< setw(6) << "E" << setw(6) << "F" << endl;
cout << " " << endl;
cout << setw(21) << "First Class" << endl;
for (a = 0; a < FC_Row; a++)
{
cout << "Row " << setw(2) << a + 1;
for (b = 0; b < FC_Col; b++)
cout << setw(5) << airplane[a][b] << " ";
cout << endl;
}
cout << setw(23) << "Economy Class" << endl;
for (a = 6; a < EconRow; a++)
{
cout <<"Row " << setw(2)<< a + 1;
for (b = 0; b < EconCol; b++)
cout << setw(5) << airplane[a][b] << " ";
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
最佳答案
你填错了。
for (a = 0; a < 100; a++)
for (b = 0; b < 6; b++)
上面的循环与文件的第一行不太匹配,其中每行没有 6 个元素。
在第一个内循环中,您会将 2, 1, 1, 1, 3, 0
读入 airplane[0]。
编辑:修复。
for (a = 0; a < FC_Row; a++)
for (b = 0; b < FC_Col; b++)
inFile >> airplane[a][b] ;
for (a = 0; a < EconRow; a++)
for (b = 0; b < EconCol; b++)
inFile >> airplane[a+FC_Row][b] ;
关于c++ - 我是填错了这个数组还是输出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266630/