T40*_*000 -1 c++ loops file 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;
}
Run Code Online (Sandbox Code Playgroud)
*******程序的输出********
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
Run Code Online (Sandbox Code Playgroud)
*** usedcars.txt **************
Toyota corolla 2005 123,000 7,999
Honda Civic 67,850 9,200
Run Code Online (Sandbox Code Playgroud)
我想你在输入"y"后按回车键进行回复.但是你只读了一个y字符.所以'\n'会被传递给下一个读取,这是您的制造商.因此那里没有数据.
正如stefaanv所写,使用cin.ignore.关于这一点可以在这里找到一个有趣的一点:清除cin输入:是cin.ignore不是一个好方法?
| 归档时间: |
|
| 查看次数: |
541 次 |
| 最近记录: |