2013-03-14 40 views
-1

我剛剛完成將數據從文本文件讀入單維數組。我的「for」語句不是從數組中輸出數據。我想輸出整個數組只是爲了驗證所有數據都在那裏。但是,當我輸出一個單獨的單元格時,數據會出現在屏幕上。我究竟做錯了什麼?提前致謝!當到達輸出一維數組中的所有數據

for (count = 0; count < MAX_CELLS; count++) { 
     cout << "Array #" << count << "is: ";  // OUTPUT ARRAY 
     cout << Vehicles[count] << endl; 
} 

在前面的循環中,您爲每條記錄遞增count所以它已經被設置爲最後記錄的索引:

#include <iostream> 
#include <fstream> 
#include <iomanip> 

int main() 
{ 
    const int MAX_CELLS = 500;  
    int count = 0;   
    double Vehicles[MAX_CELLS]; 
    ifstream vehicleFile;   
    char type; 
    string license; 
    double charge; 

    vehicleFile.open ("VEHICLE.txt"); 

    if (!vehicleFile)    
    cout << "Error opening vehicle file " << endl; 

    vehicleFile >> type >> license ;    // priming read 


    while (vehicleFile) {       // while the read was successful 

      cout << count << " " << license << endl; // FOR DISPLAY ONLY 

      vehicleFile >> Vehicles[count];    // read into array 

      count++;          // increment count 

      vehicleFile >> type >> license;    // read next line 

    } 

    cout << showpoint << fixed << setprecision(2); 


    for (count; count < MAX_CELLS; count++) { 
      cout << "Array #" << count << "is: ";  // OUTPUT ARRAY 
      cout << Vehicles[count] << endl; 
    } 


    cout << Vehicles[8];  // READS DATA IN CELL 


    vehicleFile.close(); 


    system ("pause"); 
    return 0;  
} 

回答

1

count需要重置,像這樣for循環。雖然你想要做什麼真的是用一個新的變量,只有迭代count時間:

for (int i = 0; i < count ; ++i) { 
     cout << "Array #" << i << "is: ";  // OUTPUT ARRAY 
     cout << Vehicles[i] << endl; 
} 

您還沒有檢查MAX_CELLS當你在你的數據讀取。所以如果你的文件有超過MAX_CELLS的數據,那麼你將會有未定義的行爲。

+0

Shafik,謝謝你的迴應,這很有道理。但是,由於某種原因,該程序正在崩潰。 – llSpectrell 2013-03-14 02:23:52

+0

你剛回答我的問題!我在刷新屏幕之前發佈了它。謝謝,我真的很感激! – llSpectrell 2013-03-14 02:27:06

+0

@llSpectrell對**檢查非常謹慎。你已經有一個常量來決定數組的大小。這是確保您保持在陣列範圍內的最安全的方式。 – 2013-03-14 02:34:34

0

在您的for循環中,您不會重新初始化countcount = 0)。

爲了使生活更輕鬆,並避免這類邏輯錯誤,嘗試:

for (int i = 0; i < MAX_CELLS; ++i) { 
    cout << "Array #" << i << "is: ";  // OUTPUT ARRAY 
    cout << Vehicles[i] << endl; 
} 

目前,它看起來像count已經大於或等於MAX_CELLS

1

count在while循環後仍然存在,所以它會在while循環完成後成爲最終值。然後,當它進入for循環將開始在該值:

考慮一下:

int count = 0 
while(count < 10) 
    count++ 

std::cout << "count is: " << count << std::endl; 

for (count; count < 15; count++) 
    std::cout << "now count is: " << count << std::endl 

你的輸出將是:

count is: 10 
now count is: 11 
now count is: 12 
now count is: 13 
now count is: 14 
now count is: 15 

您需要重置計數或之前for循環。