How to cope with extraneous characters left on the input stream? (cin skipped)

℡╲_俬逩灬. 提交于 2019-12-20 06:30:53

问题


Sorry for the noobish question here, but I am just learning C++ and I am looking for the standard way of dealing with this problem. I am using VS2005.

Given a program:

#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;
}

If you enter anything but an integer the program will never allow you to enter anything again. Now, I realize that this is because there is input left on the stream after the format fails, so each call to cin << i just reads up to the next end line (I think). How do you guys clear out the stream or deal with this problem? It must be pretty common.


回答1:


surround the cin call with an if.

The cin will return false if wrong data is read.

so:

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

cin.flush() should do the trick (according to cppreference.com) but not on VS apparently.

cin.clear() resets all flags to a good state. cin.ignore with a large number and until '\n' should work.




回答2:


Alright, I found the answer. The answer is...

Don't do this. Do not mix formatted and unformatted input using operator >>. Here is a good article on the subject:

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

Basically, the code changes to:

#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:


cin.ignore(int num_bytes_to_ignore); will do it.

You can also use stdio, fflush(fd); where fd is one of stdout,stderr,stdin.



来源:https://stackoverflow.com/questions/1317424/how-to-cope-with-extraneous-characters-left-on-the-input-stream-cin-skipped

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!