代码之家  ›  专栏  ›  技术社区  ›  Ed Swangren

如何处理输入流中留下的外来字符?(CIN跳过)

  •  0
  • Ed Swangren  · 技术社区  · 17 年前

    很抱歉这里的NoBISH问题,但我正在学习C++,我正在寻找处理这个问题的标准方法。我使用的是VS2005。

    给定程序:

    #include <iostream>
    
    using namespace std;
    
    int main( )
    {
        while ( true )
        {       
            cout << "enter anything but an integer and watch me loop." << endl;     
            int i;
            cin >> i;               
        }
        return 0;
    }
    

    如果输入整数以外的任何内容,程序将不再允许您再次输入任何内容。现在,我意识到这是因为格式化失败后流中仍有输入,所以每次调用CIN时,我都会读到下一行(我想)。你们是怎么解决这个问题的?这一定很常见。

    3 回复  |  直到 17 年前
        1
  •  2
  •   NomeN    17 年前

    用一个中频包围CIN呼叫。

    如果读取错误数据,CIN将返回FALSE。

    所以:

    if (!cin >> i) {
      cin.clear();
      cin.ignore(INT_MAX, '\n');
      cout << "Haha, your looping efforts have been thwarted dear sir\n";
    }
    

    cin.flush()应该完成这个技巧(根据cppreference.com),但显然不是在vs上。

    cin.clear()将所有标志重置为良好状态。 cin.ignore,用一个大的数字,直到\n'可以工作。

        2
  •  2
  •   Ed Swangren    17 年前

    好吧,我找到了答案。答案是…

    不要这样做。不要使用运算符>>混合格式化和未格式化的输入。下面是一篇关于这个主题的好文章:

    http://www.cplusplus.com/forum/articles/6046/

    基本上,代码更改为:

    #include <iostream>
    #include <string>
    #include <stream>
    
    using namespace std;
    
    int main( )
    {
        while ( true )
        {           
            cout << "enter anything but an integer and watch me loop." << endl;     
            string input;
            getline( cin, input );
            int i;
            stringstream stream( input );
            if ( stream >> i ) break;                       
        }
        return 0;
    }
    
        3
  •  0
  •   tim    17 年前

    cin.ignore(int num_bytes_to_ignore);将执行此操作。

    您还可以使用stdio、fflush(fd);其中fd是stdout、stderr、stdin之一。

    推荐文章