仅接受整数输入
Accept only integer to input
我发现这个类似的问题被问了很多次,但我仍然找不到适合我的解决方案。
就我而言,当用户输入 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');
如果发生故障,operator>>
不能保证输出有意义的整数值,但是您在评估__userChoice
之前不会检查故障,并且if
的结构方式将永远不会达到else (!cin)
检查。 但是,即使operator>>
成功,您也不会检查用户输入的不仅仅是整数。
要执行您要求的操作,您应该首先使用std::getline()
从std::cin
读取到std::string
,然后使用std::istringstream
或std: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";
}
相关文章:
- 如何打印不带空格的输入整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 如何在输入整数时中断 for 循环
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何输入整数并将其从最高到最低排序
- 如何创建一个程序,用户输入整数并输出90度数字金字塔
- 使用对输入整数的文件输入
- 使用户输入整数字符串,然后输出不同的字符串
- 从 fstream 到 2d 矢量的输入整数<矢量<int>> C++
- 用户输入整数后跟垃圾
- 输入整数直到 C/C++ 中的换行符
- 输入整数的最快方法
- C++循环 - 输入整数,直到用户退出
- 尝试输入整数行并在以矢量作为存储的函数的插入排序类型中排序
- 如何使C++程序在用户输入整数时抛出错误,而需要字符串
- 当要求输入整数并使用isdigit检查时,将char转换为int
- 如何通过指针输入整数数组并打印出数组和数组的大小(C++)
- 如果打印后输入整数,则C++分段故障,但其他情况下可以