How to cope with extraneous characters left on the

2020-05-05 17:30发布

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.

标签: c++ input
3条回答
别忘想泡老子
2楼-- · 2020-05-05 18:17

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.

查看更多
倾城 Initia
3楼-- · 2020-05-05 18:17

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.

查看更多
forever°为你锁心
4楼-- · 2020-05-05 18:23

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;
}
查看更多
登录 后发表回答