Do ... While()循环无法正常工作 [英] Do...While() loop does not work fine

查看:118
本文介绍了Do ... While()循环无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在提示用户输入有关汽车的数据。我正在使用的Do ... while()循环在第一次可以正常运行,但是在第一次之后无法正常运行。该代码是波纹管,并且我正在使用Dev-C ++。谢谢您的帮助和时间。

I am prompting the user to enter data regarding cars. The Do...while() loop I am using works fine the first time, then does not work properly after the first time. The code is bellow, and I am using Dev-C++. Thank you for your help and time.

#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;  
}

** * ** * * 程序的输出 * ** * ** * *

*******the outpu of the program********

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********** ** * *

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

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


推荐答案

我想您按Enter输入 y进行响应后。但是您只读了一个字符y。因此, n将传递给您的制造商的下一个阅读记录。因此,那里没有数据。

I suppose you press enter after entering the 'y' for response. But you only read in one character which is y. So the '\n' gets passed to the next read which is your Manufacturer. Thus there is no data there.

stefaanv写道,使用cin.ignore。可以在这里找到一个有趣的地方:清除cin输入: cin.ignore不是一个好方法吗?

As stefaanv writes use cin.ignore. An interesting bit on this can be found here: Clearing cin input: is cin.ignore not a good way?

这篇关于Do ... While()循环无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆