c++ - 验证没有字符和负输入的输入
问题描述
我正在模拟一个计算器,想知道如何只接受正输入而不接受其他字符(负整数、字母等)
我试过使用 2 个 do while 循环,一个验证正整数和另一个验证字符,但似乎不能有 2 个循环用于 1 个输入,如果没有,它看起来会很奇怪......
do{
if (invalid == true)
{
cout << "Invalid input, please enter a positive number" << endl;
}
cout << "Please enter the first number:" << endl;
cin >> num1;
cin.ignore();
invalid = true;
} while (num1 < 0);
invalid = false;
使用上面的代码,它只验证输入是否为正整数,但是一旦我输入字母等字符,程序就会崩溃。有没有办法同时排除两者?
解决方案
我的建议是将整行读取为字符串(带有std::getline
),然后尝试将字符串解析为无符号整数。
它可以实现类似
unsigned value;
for (;;)
{
std::string input;
if (!std::getline(std::cin, input))
{
// Error reading input, possibly end-of-file
// This is usually considered a fatal error
exit(EXIT_FAILURE);
}
// Now parse the string into an unsigned integer
if (std::istringstream(input) >> value)
{
// All went okay, we now have an unsigned integer in the variable value
break; // Break out of the loop
}
// Could not parse the input
// TODO: Print error message and ask for input again
// Loop continues, reading input again...
}
这可以放入一个函数来概括它,因此它可以被重用于获取多个值。您甚至可以使函数成为模板,因此它可以用于不同的输入类型(有符号或无符号整数、浮点,甚至具有合适的输入运算符>>
重载的对象)。
推荐阅读
- c# - 试图将一个数字除以数组的元素,以检查它是否是素数(有点)
- javascript - A String Describing the Additions, Removals and Changes Between Strings?
- f# - 最后一个参数是否有一些管道运算符或在 F# 中定义它的方法?
- python - Python SSL Cert error despite no browser expiry
- typescript - 打字稿:如何定义一个使用泛型引用对象的函数
- javascript - Checking if checkbox is checked: Uncaught TypeError
- node.js - Locally run Lambda would not log all outputs
- docker - 即使使用 --restart=always,Docker 也不会重新启动容器
- groovy - Groovy List
- > behaving like List
- python - 使用列名作为 x 轴绘制熊猫数据框