【发布时间】:2013-11-06 08:35:05
【问题描述】:
首先我很抱歉我的 英语不好。
我正在尝试读取一些数字并将它们写入 C++ 中的向量。 只要输入是双数并且 如果用户写入“a”,则应停止循环。
我的问题是如何检查输入是否为“a”。 打破循环不是问题
while(true){
if(!(cin>>userInput)){
//here i want to know if the input is 'a' or some other stuff//
//also i want to do some other stuff like printing everything//
//what already is in the vector//
//when everything is done; break//
}
else
//the input is a valid number and i push it into my vector//
'userInput' 被定义为双精度,因此循环将停止。 我的问题是,如果用户写 'q' 循环停止,但它会立即停止整个程序。我的尝试如下所示:
while(true){ //read as long as you can
cout<<"Input a number. With 'q' you can stop: "<<endl;
if(!(cin>>userInput)){ //here the progam stops when the input is anything but a number
cout<<"How many numbers do you want to add up?"<<endl; //there are numbers in a vector that should be added up
cin>>numberOfAdditions;
break;
}
所以我有一个向量,其中包含用户写下的一些数字(20、50、90、...) 当输入等于 'q' 时(在本例中,除了 numbers 之外的所有内容) 循环停止,我想问用户应该添加多少数字。 显示 cout 命令,但正在跳过输入。 所以我的程序没有从我想添加的向量中读取多少值。
我希望你明白我的意思,我不想使用两个问题和两个变量来保存输入,但如果没有它就无法工作,我会改变我的程序。
祝你有美好的一天:)
【问题讨论】:
-
这个帖子已经讨论过了stackoverflow.com/questions/3273993/…