从文件读取数据到数组
问题描述:
我想从一个文件读取特定数据到两个二维数组。第一行数据定义了每个数组的大小,所以当我填充第一个数组时,我需要跳过该行。在跳过第一行之后,第一个数组填充文件中的数据直到文件中的第7行。第二个数组用来自文件的其余数据填充。从文件读取数据到数组
这是我的数据文件的标记图像:
,这里是我的(有瑕疵)到目前为止的代码:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream inFile;
int FC_Row, FC_Col, EconRow, EconCol, seat;
inFile.open("Airplane.txt");
inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;
int firstClass[FC_Row][FC_Col];
int economyClass[EconRow][EconCol];
// thanks junjanes
for (int a = 0; a < FC_Row; a++)
for (int b = 0; b < FC_Col; b++)
inFile >> firstClass[a][b] ;
for (int c = 0; c < EconRow; c++)
for (int d = 0; d < EconCol; d++)
inFile >> economyClass[c][d] ;
system("PAUSE");
return EXIT_SUCCESS;
}
感谢大家的输入。
答
你的while
循环迭代直到文件结束,你不需要它们。
while (inFile >> seat) // This reads until the end of the plane.
改用(不while
):
for (int a = 0; a < FC_Row; a++) // Read this amount of rows.
for (int b = 0; b < FC_Col; b++) // Read this amount of columns.
inFile >> firstClass[a][b] ; // Reading the next seat here.
应用相同的经济席位。
此外,你可能想更改数组为矢量,因为可变大小的数组是地狱。
vector<vector<int> > firstClass(FC_Row, vector<int>(FC_Col)) ;
vector<vector<int> > economyClass(EconRow, vector<int>(EconCol)) ;
您需要#include <vector>
使用向量,它们的访问权限与数组相同。
答
您正在读入seat
,然后用此值填充数组。然后你再次读入seat
,并用这个新值填充整个数组。
试试这个:
int CurRow = 0;
int CurCol = 0;
while ((inFile >> seat) && (CurRow < FC_Row)) {
firstClass[CurRow][CurCol] = seat;
++CurCol;
if (CurCol == FC_Col) {
++CurRow;
CurCol = 0;
}
}
if (CurRow != FC_Row) {
// Didn't finish reading, inFile >> seat must have failed.
}
你的第二个循环应当使用economyClass
不firstClass
之所以围绕切换循环像这样的错误处理,这是在错误的循环退出时简化。或者,您可以保留for循环,在内部循环中使用infile >> seat
,但如果读取失败,则必须跳出两个循环。
答
您需要更改for
循环的顺序,从文件中读取:
for (rows = 0; rows < total_rows; ++ rows)
{
for (col = 0; columns < total_columns; ++cols)
{
input_file >> Economy_Seats[row][column];
}
}
我会留下检查EOF和处理无效输入给读者的。
'int firstClass [FC_Row] [FC_Col];'是一个VLA,它是C99,而不是C++。 *一些* C++编译器支持它,但对可移植性不利。 – Erik 2011-03-08 23:40:13
+1为你清晰的图解。 MSPaint从我那里获取+1 :-) – corsiKa 2011-03-08 23:44:56
+1提供您的程序的示例。 – 2011-03-08 23:46:16