【发布时间】:2019-07-24 01:57:29
【问题描述】:
我发现这个类似的问题被问了很多次,但我仍然找不到适合我的解决方案。
就我而言,我想在用户输入 1 到 5 的数字时显示一些内容,当他输入错误的内容(如字符“3g”、“3.”、“b3”和任何浮点数)时给出错误.
我尝试了下面的代码,但它产生了很多其他问题。就像我输入3g 或3.5 一样,它只会占用3 而忽略其余部分,因此(!cin) 根本不起作用。
其次,如果我输入一个字符之类的东西,__userChoice 会自动转换为0,程序会打印出"Please select a number from 1 to 5." 而不是"Invalid input, please input an integer number.\n",这正是我想要的。
cout << "Please select: ";
cin >> __userChoice;
if (__userChoice > 0 && __userChoice < 5) {
cout << "You select menu item " << __userChoice <<". Processing... Done!\n";
}
else if (__userChoice == 5) {
Finalization(); //call exit
}
else if (__userChoice <= 0 || __userChoice > 5) {
cout << "Please select a number from 1 to 5.\n";
}
else (!cin) {
cout << "Invalid input, please input an integer number.\n";
}
cin.clear();
cin.ignore(10000, '\n');
【问题讨论】:
-
__userChoice是保留标识符。您应该使用另一个变量名。