【问题标题】:Validating input with no characters and negative inputs验证没有字符和负输入的输入
【发布时间】:2019-04-02 12:17:30
【问题描述】:

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

我尝试过使用 2 个 do while 循环,一个验证正整数,另一个验证字符,但似乎 1 个输入不能有 2 个循环,否则看起来会很奇怪...

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++


【解决方案1】:

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

这可以放入一个函数中进行泛化,因此可以重用它来获取多个值。您甚至可以将函数设为模板,因此它可以用于不同的输入类型(有符号或无符号整数、浮点,甚至具有合适的输入运算符 &gt;&gt; 重载的对象)。

【讨论】:

    【解决方案2】:

    检查std::cin &gt;&gt;结果,当错误发生时清除错误然后读取一个单词(如果您愿意,您也可以阅读所有行),不要忘记管理EOF案例。

    例如

    #include <iostream>
    #include <string>
    
    int main()
    {
      int n;
    
      for (;;) {
        if (!(std::cin >> n)) {      
          // remove bad 'word'
          std::cin.clear();
          std::string s;
    
          if (!(std::cin >> s)) {
            std::cerr << "EOF" << std::endl;
            return -1;
          }
          std::cerr << "not a number" << std::endl;
        }
        else if (n < 0)
          std::cerr << "negative value" << std::endl;
        else
          break;
      }
    
      std::cout << "positive value " << n << std::endl;
    
      return 0;
    }
    

    编译和执行:

    pi@raspberrypi:~ $ g++ -pedantic -Wall -Wextra i.cc
    pi@raspberrypi:~ $ ./a.out
    aze
    not a number
    -1
    negative value
    2
    positive value 2
    pi@raspberrypi:~ $ 
    pi@raspberrypi:~ $ echo | ./a.out
    EOF
    pi@raspberrypi:~ $ ./a.out
    aze -1 23
    not a number
    negative value
    positive value 23
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多