1,105,402 Community Members

how to clear the input stream

Member Avatar
aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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!

Member Avatar
Moschops
Nearly a Posting Virtuoso
1,384 posts since Sep 2008
Reputation Points: 414 [?]
Q&As Helped to Solve: 269 [?]
Skill Endorsements: 16 [?]
Featured
 
0
 

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

Member Avatar
Ancient Dragon
Achieved Level 70
27,654 posts since Aug 2005
Reputation Points: 5,234 [?]
Q&As Helped to Solve: 3,038 [?]
Skill Endorsements: 115 [?]
Team Colleague
Featured
Sponsor
 
0
 
Member Avatar
aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

thanks a lot, it worked.

Member Avatar
aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

See this tutorial

The tutorial really helped, thanks.

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