首页 > 解决方案 > 验证没有字符和负输入的输入

问题描述

我正在模拟一个计算器,想知道如何只接受正输入而不接受其他字符(负整数、字母等)

我试过使用 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;

使用上面的代码,它只验证输入是否为正整数,但是一旦我输入字母等字符,程序就会崩溃。有没有办法同时排除两者?

标签: c++

解决方案


我的建议是将整行读取为字符串(带有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...
}

这可以放入一个函数来概括它,因此它可以被重用于获取多个值。您甚至可以使函数成为模板,因此它可以用于不同的输入类型(有符号或无符号整数、浮点,甚至具有合适的输入运算符>>重载的对象)。


推荐阅读