2011-03-08 197 views
6

我想從一個文件讀取特定數據到兩個二維數組。第一行數據定義了每個數組的大小,所以當我填充第一個數組時,我需要跳過該行。在跳過第一行之後,第一個數組填充文件中的數據直到文件中的第7行。第二個數組用來自文件的其餘數據填充。從文件讀取數據到數組

這是我的數據文件的標記圖像: enter image description here

,這裏是我的(有瑕疵)到目前爲止的代碼:

#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; 
} 

感謝大家的輸入。

+1

'int firstClass [FC_Row] [FC_Col];'是一個VLA,它是C99,而不是C++。 *一些* C++編譯器支持它,但對可移植性不利。 – Erik 2011-03-08 23:40:13

+0

+1爲你清晰的圖解。 MSPaint從我那裏獲取+1 :-) – corsiKa 2011-03-08 23:44:56

+0

+1提供您的程序的示例。 – 2011-03-08 23:46:16

回答

3

你的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>使用向量,它們的訪問權限與數組相同。

1

您正在讀入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. 
} 

你的第二個循環應當使用economyClassfirstClass

之所以圍繞切換循環像這樣的錯誤處理,這是在錯誤的循環退出時簡化。或者,您可以保留for循環,在內部循環中使用infile >> seat,但如果讀取失敗,則必須跳出兩個循環。

2

您需要更改for循環的順序,從文件中讀取:

for (rows = 0; rows < total_rows; ++ rows) 
{ 
    for (col = 0; columns < total_columns; ++cols) 
    { 
    input_file >> Economy_Seats[row][column]; 
    } 
} 

我會留下檢查EOF和處理無效輸入給讀者的。