Do…While() loop does not work fine

依然范特西╮ 提交于 2019-12-14 04:12:38

问题


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

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

回答1:


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.

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?




回答2:


the do while loop seems alright. Update your question with error or bugs that you encounter. the only problem i can think of from the code is that the stream isnt closed after iteration. you have to close the stream when user response is n



来源:https://stackoverflow.com/questions/9733438/do-while-loop-does-not-work-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!