将数据从文件读入数组

dar*_*rko 6 c++

我试图将文件中的特定数据读入两个2D数组.第一行数据定义了每个数组的大小,所以当我填充第一个数组时,我需要跳过该行.跳过第一行后,第一个数组将填充文件中的数据,直到文件中的第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;
}
Run Code Online (Sandbox Code Playgroud)

感谢大家的意见和建议.

Tug*_*tes 3

您的while循环会迭代直到文件末尾,您不需要它们。

while (inFile >> seat) // This reads until the end of the plane.
Run Code Online (Sandbox Code Playgroud)

改为使用(不带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.
Run Code Online (Sandbox Code Playgroud)

经济舱座位也同样适用。


另外,您可能希望将数组更改为向量,因为可变大小的数组是地狱。

vector<vector<int> > firstClass(FC_Row, vector<int>(FC_Col)) ;
vector<vector<int> > economyClass(EconRow, vector<int>(EconCol)) ;
Run Code Online (Sandbox Code Playgroud)

您需要#include <vector>使用向量,它们的访问与数组相同。