[英]using cin.ignore()? Not sure how to make it work
bool showMenu(romanType roman){
cout << endl;
cout << "Just enter a number to choose an option" << endl;
cout << "1: Print the Roman Numeral" << endl;
cout << "2: Print the decimal value" << endl;
cout << "3: Enter a new Roman Numeral" << endl;
cout << "4: Quit the program" << endl;
cout << endl;
while (true) {
cout << "Your choice:" << endl;
int input;
cin >> input;
if (input == 1) {
cout << roman.getRomanString() << endl;
} else if(input ==2) {
cout << roman.getDecimalValue() << endl;
} else if(input == 3) {
return true;
} else if(input == 4) {
return false;
} else {
cout << "Invalid selection, please make a valid selection." << endl;
}
}
}
下车,总的来说这很好用,我只是在我的最后一句话中遇到一个小问题。 只要用户输入了一种int类型,循环就会按照预期的方式执行,但是如果输入任何类型的字符串(即45r,rts,3e5),循环将停止用户输入并且无限旋转,cout( ing)选择无效...和你的选择......一遍又一遍。 我想我需要使用.ignore()在字符串的情况下删除\\ n,但我不知道该怎么做。 我是在正确的轨道上吗?
是的,你走在正确的轨道上。
cin >> input
尝试提取整数。 如果失败,则不从cin
中提取符号,并设置failbit。 在这种情况下,提取将不再起作用。 您必须ignore
其余的用户输入并clear
错误位:
} else {
cout << "Invalid selection, please make a valid selection." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
// numeric_limits<streamsize>::max() returns the maximum size a stream can have,
// see also http://www.cplusplus.com/reference/std/limits/numeric_limits/
}
另请参阅为什么这个cin读数卡住了? 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.