【问题标题】:Error handling in C++C++ 中的错误处理
【发布时间】:2010-09-30 12:22:50
【问题描述】:

如何使 cin 语句只接受整数?

【问题讨论】:

  • “只接受整数”到底是什么意思?具体来说,当/如果用户输入其他内容(例如,字母或标点符号)时,您希望发生什么?
  • cin 是一个通用对象,您不能将其修改为仅提供整数。您可以修改程序以仅接受整数。要么编写你自己的过滤版本的cin,要么编写一些只从文件中获取整数并将文件传递给你的程序的东西。

标签: c++


【解决方案1】:

我认为您不能强制std::cin 在所有情况下都拒绝接受非整数输入。你总是可以写:

std::string s;
std::cin >> s;

因为字符串不关心输入的格式。但是,如果您想测试读取整数是否成功,您可以使用fail() 方法:

int i;
std::cin >> i;
if (std::cin.fail())
{
   std::cerr << "Input was not an integer!\n";
}

或者,您可以只测试cin 对象本身,这是等效的。

int i;
if (std::cin >> i)
{
   // Use the input
}
else
{
   std::cerr << "Input was not an integer!\n";
}

【讨论】:

  • “我不认为你可以在全局范围内做这样的事情”,你可以设置cin.exception(ios::failbit)来全局应用它。
  • @ybungalobill 即使使用异常掩码,您也可以成功读取其他类型 (std::string s; std::cin &gt;&gt; s;)。据我所知,在尝试读取非整数类型时(即使输入格式正确),没有办法强制 operator&gt;&gt;总是失败。
  • 啊,我知道现在措辞是多么混乱。编辑。
  • 这里的问题是它不能完全确定它是一个 int。如果您输入 10.5,它将被截断并转换为 int。这可能不是您所期望或想要的。重要的是要意识到 >> 是类型安全的,并且理解类型转换是如何工作的。
【解决方案2】:
#include <iostream>
#include <limits>
using namespace std;

int main(){
   int temp;
   cout << "Give value (integer): ";
   while( ! ( cin >> temp ) ){
      cout << "That was not an integer...\nTry again: ";
      cin.clear();
      cin.ignore( numeric_limits<streamsize>::max(), '\n' );
   }
   cout << "Your integer is: " << temp;
}

发现此来源:http://www.dreamincode.net/forums/topic/53355-c-check-if-variable-is-integer/ 我昨天才需要这样做:)

【讨论】:

    【解决方案3】:

    另一种使用 std::cin 的方法。

    #include <iostream>
    #include <limits>
    
    using namespace std;
    
    int main()
    {
    
        double input;
        while (cin)
        {
            cout << "Type in some numbers and press ENTER when you are done:" << endl;
            cin >> input;
            if (cin)
            {
                cout << "* Bingo!\n" << endl;
            }
            else if (cin.fail() && !(cin.eof() || cin.bad()))
            {
                cout << "* Sorry, but that is not a number.\n" << endl;
                cin.clear();
                cin.ignore(numeric_limits<std::streamsize>::max(),'\n');
            }
        }
    }
    

    g++ -o num num.cpp

    【讨论】:

      【解决方案4】:

      将 cin 放入 while 循环中,然后进行测试。

      cin.exceptions(ios::failbit | ios::badbit );
      int a;
      bool bGet = true;
      while(bGet)
      {
        try
        { 
          cin >> a;
          bGet = false;
        }
        catch
        { ; }
      }      
      

      【讨论】:

      • operator&gt;&gt; 在这种情况下不会抛出异常,除非您使用 ios::exceptions 设置标志
      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多