【问题标题】:Testing for an integer in c++在 C++ 中测试整数
【发布时间】:2014-02-05 02:25:07
【问题描述】:

我正在尝试编写一个 c++ 程序来测试每个输入整数,如果输入无效则停止。

这是我的代码,没有测试部分:

#include <iostream>
#include <stdlib.h>
    using namespace std;

int main()
{
    int i;

    do
    {   
        cout << "\nPlease enter an integer: ";
        cin >> i;   
        cout << endl << i << endl;

    } while(i != 0);

    system("Pause");
    return 0;
}

如何测试输入的有效性?

【问题讨论】:

  • while(!(std::cin &gt;&gt; i)) { /* invalid input */ } 可能就是您想要的。
  • 循环必须是一个do while,如果输入也是一个浮点数则它必须失败

标签: c++ validation input integer


【解决方案1】:

最简单的方法是使用std::getline 将整个输入行读入std::string,然后测试该字符串是否是有效的整数规范。

也可以通过测试 cin 的故障状态并清除它来做到这一点,但这样会带来各种你不想要的复杂情况。

为了测试字符串,您可以使用高级std::istringstream(只需从中读取并测试其故障状态),或者更有效但更复杂一点,来自C库的strtol(后者是 C++ 流内部使用的内容)。

【讨论】:

    【解决方案2】:

    您需要在不崩溃的情况下测试字符串是否为整数。

    您可以使用strtol() 执行此操作。它将字符串转换为整数,并报告不是数字的合法字符的第一个字符。没有无效字符意味着整个字符串是一个整数。

    这里有一个很好的描述和如何使用它的例子:

    http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <stdlib.h>
         using namespace std;
      
      int main()
      {
          int i;
      
          do
          {   
              cout << "\nPlease enter an integer: ";
      
              while(!(cin >> i))
              {
                  cin.clear();
                  cin.ignore();
                  cout << "\nInput was invalid, please re-enter: ";
              }
      
              cout << endl << "The integer is: " << i << endl;
      
      
          } while(i != 0);
      
          system("Pause");
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-04
        • 2010-12-17
        • 2020-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多