且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理输入流中剩余的多余字符? (cin跳过了)

更新时间:2023-11-12 11:48:04

好的,我找到了答案.答案是...

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/

基本上,代码更改为:

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