Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trapping a character input on a double with cin

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I have a program that is expecting a double from a cin statement. I want to make sure it doesn't go into an infinite loop if someone enters a character instead. I am just starting at C++ in school. Thanks.
 
while(TRUE)
{
cout << &quot;\nEnter an integer: &quot;;
cin >> i;
if(cin.good()) // if no errors
{
cin.ignore(10,'\n'); // remove newline
break; // exit loop
}
cin.clear(); // clear error bits
cout << &quot;Incorrect input&quot; << endl;
cin.ignore(10,'\n'); // remove newline
}
cout << &quot;Integer is &quot; << i << endl; // echo error free int


The above is for an int but works for doubles, float, and long double. You just need to check the goodbit (TRUE if all is OK).

Brother C


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top