如何处理输入流中剩余的多余字符? (cin跳过了) [英] How to cope with extraneous characters left on the input stream? (cin skipped)

查看:197
本文介绍了如何处理输入流中剩余的多余字符? (cin跳过了)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这里的问题很棘手,但是我只是在学习C ++,我正在寻找处理此问题的标准方法.我正在使用VS2005.

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.

给出一个程序:

#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<<我只是读到下一个终点线(我认为).你们如何清除流或处理此问题?这一定很常见.

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.

推荐答案

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

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

这篇关于如何处理输入流中剩余的多余字符? (cin跳过了)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆