2011-03-10 182 views
3

我正在使用文本文件中的數據填充數組的程序。當我輸出數組時,其內容並不按照我認爲讀入的順序排列。我在考慮問題是在將數據輸入到數組中還是將數組輸出到iostream的for循環中。任何人都能發現我的錯誤嗎我是填寫這個數組錯誤還是輸出錯了?

數據

(I改變第一數量每行中,以2-31從0和1的區別開來) enter image description here

輸出

enter image description here

該代碼

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

回答

1

你填錯了。

for (a = 0; a < 100; a++)  
    for (b = 0; b < 6; b++) 

上面的循環與您的文件的第一行不匹配得很好,其中每行沒有6個元素。

在第一個內循環中,您會將2, 1, 1, 1, 3, 0讀入飛機[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] ; 
+0

蕩它,這就是爲什麼我用2個數組,但最初的要求只是想一個數組!我將如何解決這個問題? – darko 2011-03-10 22:30:31

+0

我在你之前關於這個循環的問題中建議的方式:P - http://stackoverflow.com/questions/5239689/reading-data-from-file-into-array - 只使用一個數組,並且不要重置CurRow之後閱讀第一課 – Erik 2011-03-10 22:31:44

+0

更新了建議的修復程序。這沒有任何錯誤檢查,我仍然認爲你的其他Q的循環機制會更好。 – Erik 2011-03-10 22:37:14

1

您的代碼填充所述數組:

for (a = 0; a < 100; a++)  
     for (b = 0; b < 6; b++) 
      inFile >> airplane[a][b] ; 

假定在每行中的6列,沒有,只有4在第一6行的行。

0

所以你填寫的是一個100x6的數組,但前幾行數據只有4列數據。

一個更好的辦法是這樣的:

for (a = 0; a < 100; a++)  
     for (b = 0; b < 6; b++) 
     { 
      char c; 
      inFile>>c; 
      if (c is new line){ 
      break; 
      } 

      //fill in the 2d array 
     } 
0

這裏正確的做法是在用的std ::函數getline時間在一條線上閱讀。然後解析每一行,與您的方式類似,儘管您可能想使用矢量而不是二維數組。

如果你有一個載體向量,你會發現內部向量不需要都具有相同的大小,事實上它們不應該在你的情況下。

事實上,我沒有得到的是您正在閱讀的EconRow和EconCol的值,但硬編碼您的數組大小。

有了載體,你將能夠靈活地將其設置爲值,你已經讀入。

相關問題