读书人

整理过后重发帖:清空输入流解决方法

发布时间: 2012-04-08 14:38:30 作者: rapoo

整理过后,重发帖:清空输入流

C/C++ code
#include<iostream>#include<vector>#include<stdexcept>#include<cstdio>using namespace std; void keep_window_open(){    cin.clear();    [color=#FF0000]cout<<unitbuf; //就是这个地方,我想将输入流彻底清空,不知道用什么方法[/color]        cout << "Please enter a character to exit\n";    char ch;    cin >> ch;    cout <<ch <<endl;    return;}int main()    try{    vector<int> v;    int x;        while(cin>>x)     {        v.push_back(x);    }        for(int i=0;i<=v.size();i++)        cout<<"v["<<i<<"]=="<<v.at(i)<<endl;}catch (exception& oor) {   cerr << "Out of Range error: " << oor.what() << endl;    keep_window_open();    return 1;    }catch(...){    cerr<<"exception :something went wrong\n";    return 2;}

请大家回复前先认真看一下我的程序~
输入city@ubuntu:~/Desktop/temp$ ./hh
11
22
s
结果:v[0]==11
v[1]==22
Out of Range error: vector::_M_range_check
Please enter a character to exit
s
大家可以看到我是用输入一个字符来结束 while(cin >>x)输入的,但是字符s 还是在输入流中,并在keep_window_open()里赋值给了ch。
我的问题就是怎样在 cin >>ch 这步之前清空输入流??
目前根据大家的回复,我尝试了下面几种方法:
1)cout.flush() cout<<flush flush(cout)都不行。貌似这几个是等价的,我查看了一下,发现这几个都是情况输出流的
2)cin.clear() ; cin.sync(); 这个也不行,但我不知道为什么? cin.sync()的用途是: the unread characters in the buffer are discarded. 求大牛解释
3)cin.ignore(cin.gcount()+1);这个只能清空一个字符时的输入流,如果输入流里是一个字符串,那么这个方法还是会保留下第一个字符。同样不知道为什么???求解释
4)rewind(stdin);这个是赵中老师的方法,他说可以,但是放在我的程序里就是不行,而且不想用scanf。求赵老师根据我的程序给改改吧~~~
5)cout<<unitbuf; 这个也木有用啊~~~unitbuf的解释如下:
Sets the unitbuf "format" flag for the str stream.
When the unitbuf flag is set, the associated buffer is flushed after each insertion operation.

非常感谢提供以上方法的大牛,虽然还木有把我的问题彻底解决~~
希望大家提供更多的有效可行的方法!!!!


[解决办法]
楼主这个例子充分说明C++异常处理能不用最好不用。
C/C++ code
#include <iostream>#include <vector>#include <cstdio>using namespace std;void keep_window_open(){    cout << "Please enter a character to exit\n";    char ch;    rewind(stdin);    ch=getchar();    cout << ch <<endl;    return;}int main() {    vector<int> v;    int x,r;    while (1) {        r=scanf("%d",&x);        if (1==r) {//输入一个整数回车            v.push_back(x);        } else if (0==r) {            cerr << "Invalid input!" << endl;            keep_window_open();            return 1;        } else if (EOF==r) {//输入Ctrl+Z回车            break;        } else {            cerr << "exception :something went wrong\n";            return 2;        }    }    for (int i=0;i<=v.size();i++)        cout << "v[" << i << "]==" << v.at(i) << endl;    return 0;}//11//22//s//Invalid input!//Please enter a character to exit//a//a
[解决办法]
先调用cin.clear(),然后调用cin.sync()。
当程序想要去读一个int型却读到了一个char型输入的时候,cin就会将自己的内部错误标识符设定为ios::failbit(没有错误是ios::goodbit),cin.clear()的作用不是清空输入缓冲区,而是清空这个内部错误标识符,真正清空输入缓冲区的是cin.sync(),但是只清空缓冲区也不行,因为内部错误标识符还保留着呢,下次读取的时候一看上次有错误,这次根本不读了,所以一定要一起调用。

读书人网 >C++

热点推荐