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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

int error checking problem

Status
Not open for further replies.

rexall

Programmer
Oct 28, 2000
6
0
0
US
Can anyone tell me how to have a user input an int from the keyboard and error check it so that the int is actually a number and the user can keep trying until he/she gets it right? I tried using loops but apparently it screws up the input stream pretty bad and causes infinite iteration. I know how to check if it's a # but how do I do it until it gets done right? Somebody please help me!!!!
 
Show us some of the code in question. How are you getting the streams? How are you looping?

James P. Cottingham

All opinions are mine alone and do not necessarily reflect those of my employer.
 
For example:

int a;

do {
cout << &quot;Enter an integer: &quot;;
cin >> a;
} while (!isdigit(a));

This causes the programming to keep iterating the do-while loop forever. I just can't think of anything to handle this problem.
 
zBuilder's suggestion is what I would suggest. cin is buffering everything until it gets a RETURN and then presents it to a. If you are required to use the loop, make a a char and use getchar (or a variant). Then use can use isdigit.


James P. Cottingham

All opinions are mine alone and do not necessarily reflect those of my employer.
 
Hi rexall

if the target var is say type int, you could try checking the stream state, ie for an int an input of type char will flag the fail bit of the stream flag indicating an error this is a technique i use for checking user input (when you must us stream based input as opposed to getch() or similar)
you can work this into a loop

in >> a.aValue.minutes; // get user input
if (!in.fail() && in.peek() == '\n'){
if(a.CheckLimits(a.aValue.minutes, 0, 60, 2)){
gotoxy(1,10); // locate cursor for this data entry
clreol(); // clear the current display line
cout << prompt_enter << prompt_decl_mn << minminutes
<< prompt_thingy << prompt_to << maxminutes
<< prompt_thingy << a.declination.minutes;
break; // lets get out of here and get the next
item
}
} // end if not in.fail()

CheckLimits is a member function >=0 and <60 and 2 digits

HTH
Robert


Robert Dwyer
rdwyer@orion-online.com.au
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top