【问题标题】:how to clear the stdin stream如何清除标准输入流
【发布时间】:2012-03-19 01:22:15
【问题描述】:
#include<iostream>
#include<vector>
#include<stdexcept>
#include<stdio.h>

using namespace std;

 void keep_window_open()
{   
    cin.clear();        //clear badbit flag
    cin.sync();        //clear stdin stream

    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;    //out of range

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

上面的代码是练习C++异常处理函数的。

然而,该程序在 Ubuntu 11.04 下清除标准输入流点时无法正常运行,但在 Windows 下的 Codeblocks 下运行良好。怎么了?

另外,为什么是“fflush(stdin);”不能替换“cin.clear(); cin.sync();”吗?如果有其他方法可以清除流?

感谢您的帮助!

【问题讨论】:

  • 你为什么要这样做?除了读取所有数据之外,我认为没有一种好的、更不用说可移植的方式来“清除”STDIN。

标签: c++ exception


【解决方案1】:

请阅读此常见问题解答条目

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1052863818&id=1043284351

为什么 fflush(stdin) 是错误的

还有这个

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392

刷新输入缓冲区

【讨论】:

  • 你知道为什么我的代码在 Codeblocks 中可以在 Windows 下正常运行,但在 Linux 下运行错误,都使用 GNU GCC 编译器吗?这个问题让我困惑了很长时间。感谢您的帮助!
  • @city,如果您仍然想知道,我坚信这是由于致电cin.sync()。该功能不能保证按照它所说的那样做,我认为它不会在 Linux 上做。不幸的是,我知道没有更好的定义明确的方法不涉及知道那里是否已经存在某些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2016-08-11
  • 1970-01-01
  • 2019-09-25
  • 2013-05-30
相关资源
最近更新 更多