仅接受整数输入

Accept only integer to input

本文关键字:输入 整数      更新时间:2023-10-16

我发现这个类似的问题被问了很多次,但我仍然找不到适合我的解决方案。

就我而言,当用户输入 1 - 5 之间的数字时,我想显示一些东西,当他输入错误的东西(如字符、"3g"、"3."、"b3"和任何浮点数)时给出错误。

我尝试了下面的代码,但它产生了许多其他问题。就像我输入3g3.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');

如果发生故障,operator>>不能保证输出有意义的整数值,但是您在评估__userChoice之前不会检查故障,并且if的结构方式将永远不会达到else (!cin)检查。 但是,即使operator>>成功,您也不会检查用户输入的不仅仅是整数。

要执行您要求的操作,您应该首先使用std::getline()std::cin读取到std::string,然后使用std::istringstreamstd:stoi()(或等效)将string转换为具有错误检查的int

例如:

bool strToInt(const std::string &s, int &value)
{
std::istringstream iss(s);
return (iss >> value) && iss.eof();
// Or:
std::size_t pos;
try {
value = std::stoi(input, &pos);
}
catch (const std::exception &) {
return false;
}
return (pos == input.size());
}
...
std::string input;
int userChoice;
std::cout << "Please select: ";
std::getline(std::cin, input);
if (strToInt(input, userChoice))
{
if (userChoice > 0 && userChoice < 5)
{
std::cout << "You selected menu item " << userChoice <<". Processing... Done!n";
}
else if (userChoice == 5)
{
Finalization(); //call exit
}
else
{
std::cout << "Please select a number from 1 to 5.n";
}
}
else
{
std::cout << "Invalid input, please input an integer number.n";
}