2013-08-03 141 views
0

我試圖從輸入文件打印,當時只有一組條目,但當我嘗試打印它,它顯示它兩次,我不能找出原因。任何幫助,將不勝感激。繼承人代碼試圖從輸入文件打印,但打印最後輸入兩次

ifstream orders;  
int idNum = 0; 
int quantity = 0; 
double totalCost = 0; 

orders.open("processedOrders.dat"); 
if (orders.is_open()) 
{ 
cout << "Order Number" << setw(16) << "Quantity" << setw(22) << "Total Cost" << endl; 
    while (!orders.eof()) 
    { 
     orders >> idNum >> quantity >> totalCost; 
     cout << " " << idNum << setw(18) << quantity << setw(23) << totalCost << endl; 
    } 
     orders.close(); 
} 
+0

你在計算器上搜索呢? – P0W

+0

'while(!orders.eof())'不會做你認爲的事 – billz

+0

我相信這會揭示你的問題 - > http://mathbits.com/MathBits/CompSci/Files/End.htm –

回答

3

EOF標記尚未讀取,因此需要進行下一次迭代,因此需要最後一行兩次。

檢查循環內EOF,像這樣: -

if (orders.is_open()) 
{ 
cout << "Order Number" << setw(16) << "Quantity" << setw(22) << "Total Cost" << endl; 
    while (true) 
    { 
     orders >> idNum >> quantity >> totalCost; 
     if(orders.eof()) break; 
     cout << " " << idNum << setw(18) << quantity << setw(23) << totalCost << endl; 
    } 
     orders.close(); 
} 

繼也應達到預期的結果:

if (orders.is_open()) 
while (orders >> idNum >> quantity >> totalCost) 
    cout << " " << idNum << setw(18) << quantity << setw(23) << totalCost << endl;