Do ... while()循环不能正常工作

时间:2012-03-16 07:25:55

标签: c++ file loops do-while

我提示用户输入有关汽车的数据。我正在使用的Do ... while()循环第一次正常工作,然后在第一次之后无法正常工作。代码如下,我正在使用Dev-C ++。感谢您的帮助和时间。

#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

2 个答案:

答案 0 :(得分:6)

我想你在输入“y”后按回车键进行回复。但是你只读了一个y字符。所以'\ n'会被传递给下一个读取,这是您的制造商。因此那里没有数据。

正如stefaanv所写,使用cin.ignore。关于这一点可以在这里找到:Clearing cin input: is cin.ignore not a good way?

答案 1 :(得分:1)

do while循环似乎没问题。使用您遇到的错误或错误更新您的问题。 我能从代码中想到的唯一问题是迭代后流不是关闭的。当用户responsen

时,您必须关闭该流