如何清除stdin流 [英] how to clear the stdin stream
问题描述
#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<< 请输入要退出的字符\\\
;
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<< 超出范围错误:< oor.what()<< endl;
keep_window_open();
return 1;
} catch(...){
cerr<<exception:something gone wrong\\\
;
return 2;
}
上面的代码是练习C ++异常处理函数。
但是,在Ubuntu 11.04下清除stdin流点时程序无法正常运行,但在Windows下的代码块中运行良好。
此外,为什么fflush(stdin); can not substitudecin.clear(); cin.sync();?
请阅读此常见问题条目
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
刷新输入缓冲区 $ b
#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;
}
the code above is to practice the C++ exception handler function.
However, the program couldn't run correctly at clearing stdin stream point under Ubuntu 11.04, but function well under Windows in Codeblocks . What's wrong?
Besides, why "fflush(stdin);" couldn't substitude "cin.clear(); cin.sync();"? And if there are other methods to clear streams?
thanks for your help!
Please read this FAQ entry
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1052863818&id=1043284351
Why fflush(stdin) is wrong
and this
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392
Flush the input buffer
这篇关于如何清除stdin流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!