#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