c ++ cin输入不工作? [英] c++ cin input not working?
本文介绍了c ++ cin输入不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include< iostream>
#include< string>
struct Car {
std :: string model;
unsigned int year;
};
int main(){
using namespace std;
int carNum;
cout<< 你想要多少辆汽车?;
cin>> carNum;
Car * cars = new Car [carNum];
for(int i = 0; i cout< Car#<< i<< endl;
cout<< 请输入make:;
getline(cin,cars [i] .model);
cout<< 请输入年份:;
cars [i] .year = cin.get();
}
cout<< 这里是您的收藏< endl;
for(int i = 0; i cout<汽车[i] .model< <汽车[i] .year< endl;
}
delete [] cars;
return 0;
}
当我执行程序时, getline ,car [i] .model)
刚刚跳过。为什么呢?
像这样:
Car#2
请输入make:请输入年份:
解决方案
简单的原因。
cin>无论
,都会留下一个 \\\
(按下Enter时添加)。默认情况下,
getline
读取到下一个 \\\
,因此下一个读取将只读取一个空字符串。 / p>
解决方法是舍弃 \\\
。您可以执行此操作:
cin.ignore(numeric_limits< streamsize> :: max(),'\\\
');
刚刚在 cin>
不要忘记包含 limits
c $ c> numeric_limits 。
#include <iostream>
#include <string>
struct Car{
std::string model;
unsigned int year;
};
int main(){
using namespace std;
int carNum;
cout << "How many cars do you wish you catalog? ";
cin >> carNum;
Car * cars = new Car[carNum];
for (int i=0;i<carNum;i++){
cout << "Car #" << i << endl;
cout << "Please enter the make: ";
getline(cin, cars[i].model);
cout << "Please enter the year made: ";
cars[i].year = cin.get();
}
cout << "Here's your collection" << endl;
for (int i=0;i<carNum;i++){
cout << cars[i].model << " " << cars[i].year << endl;
}
delete [] cars;
return 0;
}
When i execute the program, the getline(cin, car[i].model)
just get skipped over. Why is this?
like this:
Car #2 Please enter the make: Please enter the year made:
解决方案
Simple reason.
When you do cin >> whatever
, a \n
is left behind (it was added when you pressed Enter). By default, getline
reads until the next \n
, so the next read will simply read an empty string.
The solution is to discard that \n
. You can do it by putting this:
cin.ignore(numeric_limits<streamsize>::max(),'\n');
Just after the cin >> carNum
.
Don't forget to include limits
in order to use numeric_limits
.
这篇关于c ++ cin输入不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文