2014-03-30 72 views
0

任何人都可以修復此示例代碼,該代碼將打印2D數組中的文件。這裏是代碼和輸出。使用二維數組打開流

while (!file.eof()) 
{ 
    int counter =0; 
    file>>n; 

    cout<< setw(4)<< n << " ";  

    if (counter == 5) 
    {   
     cout << endl; 
     counter = 0; 
     counter ++; 
     } 

    } 
} 

輸出不是表格形式。

的輸出是:

指數大小重量(磅/英尺)直徑(英寸)0 2 0.167 0.250 1 3 0.376 0.375 2 4 0.668 0.500 3 5 1.043 0.625 4 7 1.502 0 6 9 2.670 1.000 7 12 3.400 1.128 8 14 4.303 1.270 1.270

按任意鍵繼續。 。 。

+0

你設置'計數器= 0'在循環的每次迭代的頂部,所以它永遠不會達到5 ...移動你的'計數器'變量的定義在循環之前...而且,如果它已經是5,你只會增加它,所以還有另一個原因,它永遠不會達到5 ... – twalberg

回答

0

兩個選項:

定義coutner靜態

while (!file.eof()) 
{ 
    static int counter =0; 
    file>>n; 

    cout<< setw(4)<< n << " ";  

    if (counter == 5) 
    {   
     cout << endl; 
     counter = 0; 
     counter ++; 
     } 

    } 
} 

還是有它定義外部while循環:

int counter = 0; 

while (!file.eof()) 
{ 

    file>>n; 

    cout<< setw(4)<< n << " ";  

    if (counter == 5) 
    {   
     cout << endl; 
     counter = 0; 
     counter ++; 
     } 

    } 
} 

如果你定義它和以往任何時候都初始化爲0 iteratoin的while循環 - 它永遠不會達到5打印endl;

0

似乎不像其他人指出的那樣,在每個循環中初始化計數器,而且實際上從未實際增加計數器。我看到的唯一增長是在等於五的情況下。由於它在條件之外永遠不會增加,所以它永遠不會達到五(即使它被聲明爲靜態或在循環之外),因此從未滿足條件。

您的開啓和關閉花括號也有不均勻的數量。

我不完全確定你想達到什麼。如果你想每五迭代後換行,下面應該工作:

int counter = 0; 
cout << setw(4) // suffice to set once 

while (!file.eof()) 
{ 
    file >> n; 

    cout << n << " "; 

    if (++counter == 5) // increase here before checking condition 
    {   
     cout << endl; 
     counter = 0; 
     // do not increase here again 
    } 
}