We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,965 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

how to clear the input stream

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!

3
Contributors
4
Replies
1 Day
Discussion Span
1 Year Ago
Last Updated
5
Views
aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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

Moschops
Practically a Posting Shark
888 posts since Sep 2008
Reputation Points: 297
Solved Threads: 170
Skill Endorsements: 5
Ancient Dragon
Achieved Level 70
Team Colleague
32,123 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69

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

thanks a lot, it worked.

aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

See this tutorial

The tutorial really helped, thanks.

aderogba08
Newbie Poster
7 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0812 seconds using 2.71MB