2012-03-16 138 views
-1

我在提示用戶輸入有關汽車的數據。 Do ... while()循環我第一次使用時工作正常,然後在第一次後無法正常工作。代碼如下,我正在使用Dev-C++。感謝您的幫助和時間。做... while()循環不能正常工作

#include <iostream> 
#include<conio.h> 
#include<cstring> 
#include<fstream> 
#include <iomanip.h> 


using namespace std; 

int main() 
{ 

    char manufacturer[16], model[16], year[10], miles[10], car_cost[12]; 
    char response; 
    ofstream OS ("usedcars.txt", ios::out); 
    cout<<"for each car please enter :"<<endl; 

    do 
    { 
    ofstream OS ("usedcars.txt", ios::app); 
    cout<<"The manufacturer: "; 
    cin.getline(manufacturer, 16); 
    cout<<"The model: "; 
    cin.getline(model, 16); 
    cout<<"The year: "; 
    cin.getline(year, 8); 
    cout<<"The miles: "; 
    cin.getline(miles, 8); 
    cout<<"The cost of car $: "; 
    cin.getline(car_cost, 10); 

    OS << manufacturer << setw(9) << model << setw(8) << year << setw(11)<< miles << setw(8) << car_cost << endl; 
    cout<<"Do you want to continue?"; 
    cin>>response; 

} 
while (response!='n'); 


    return 0; 
} 

** * ** * *程序的outpu* ** * ** * *

for each car please enter : 
The manufacturer: Toyota 
The model: corolla 
The year: 2005 
The miles: 123,000 
The cost of car $: 7,999 
Do you want to continue?y 
The manufacturer: The model: Honda 
The year: Civic 
The miles: 67,850 
The cost of car $: 9,200 
Do you want to continue?n 

** *usedcars.txt* ** * ** * ** * ** * *

Toyota corolla 2005 123,000 7,999 
    Honda Civic  67,850 9,200 
+3

*第一次後不能正常工作*它掛起,它崩潰,它飛走了,它爆炸了嗎?除非你明確地告訴我們,否則我們應該如何知道? – 2012-03-16 07:28:56

+1

不,我猜它「死於火焰」:) – sirgeorge 2012-03-16 07:33:16

+0

我認爲文件usedcars.txt是空的或可能是它被讀取錯誤 – Ben 2012-03-16 07:36:34

回答

6

我猜想在輸入'y'作爲迴應後按回車鍵。但是你只能閱讀一個字母y。所以'\ n'被傳遞給下一次讀取,這是您的製造商。因此,那裏沒有數據。

由於stefaanv寫使用cin.ignore。關於此的一個有趣的位可以在這裏找到:Clearing cin input: is cin.ignore not a good way?

+2

通過在第一個cin.getline之前添加一個cin.ignore調用來解決這個問題, – stefaanv 2012-03-16 07:36:00

+0

+1用於猜測「不起作用」 – OSH 2012-03-16 07:36:10

+0

的含義是否會發生在cin中? – 2012-03-16 07:39:58

1

do while循環看起來沒問題。用您遇到的錯誤或錯誤更新您的問題。 我能從代碼中想到的唯一問題是迭代後流不會關閉。當用戶responsen

+0

在第一個getline()之前我錯過了一個cin.ignore。它現在工作正常。正如你所提到的,我將關閉這個流。再次感謝! – T4000 2012-03-16 07:44:20

+0

哦好吧!下次更好的問題請 – 2012-03-16 07:46:18