1.11M Members

how to clear the input stream

 
0
 

I wrote a program that allow users input a double value, if I input a string or a char value, it turns out to be a logical error. I've tried this:

bool h;
float value;
do{
cout<<"enter a value"<<endl;
cin>>value;
if(cin.fail()){
cout<<"error, enter a value!"<<endl;
cin.clear();
cin.ignore();
h=true;}
else
h=false;
}
while(h==true);

If I input "mee" for instance it gives me "error, enter a value!" thrice instead of once. I thought cin.ignore(), cin.clear() is used to erase the input stream. Thanks in advance!

 
0
 

Try
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

 
0
 
 
0
 

Try
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

thanks a lot, it worked.

 
0
 

See this tutorial

The tutorial really helped, thanks.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article