简体   繁体   English

可以…虽然()循环无法正常工作

[英]Do…While() loop does not work fine

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. 我正在使用的Do ... while()循环在第一次可以正常运行,但是在第一次之后无法正常运行。 The code is bellow, and I am using Dev-C++. 该代码是波纹管,并且我正在使用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

I suppose you press enter after entering the 'y' for response. 我想您在输入“ y”后按回车。 But you only read in one character which is y. 但是您只读了一个字符y。 So the '\\n' gets passed to the next read which is your Manufacturer. 因此,“ \\ n”将传递给您的制造商的下一个读取项。 Thus there is no data there. 因此,那里没有数据。

As stefaanv writes use cin.ignore. 正如stefaanv所写,请使用cin.ignore。 An interesting bit on this can be found here: Clearing cin input: is cin.ignore not a good way? 可以在这里找到一个有趣的地方: 清除cin输入:cin.ignore不是一个好方法吗?

the do while loop seems alright. do while循环看起来还不错。 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 您必须在用户responsen时关闭流

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM