|
-
Jul 13th, 2003, 03:06 PM
#1
Thread Starter
Addicted Member
user input
If i want to have the user input an integer, how can i prevent them from entering a character without getting a run-time error?
To understand recursion, one must first understand the concept of recursion.
-
Jul 13th, 2003, 03:07 PM
#2
Stuck in the 80s
What I usually do (and I doubt it's the best method), is have it input to a char, and then cast it to an integer, if it's valid.
-
Jul 13th, 2003, 03:45 PM
#3
Hyperactive Member
You could handle the error... I usually just put user input into a while loop and have a function check to see if an error has occured in cin. I can't explain it very well, here's some code:
This is the function I use to check cin.
Code:
short ErrChk()
{
if(cin.fail())
{
cerr << "\nInput Error! Clearing buffer... \n";
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
return 0;
}
else
{
return 1;
}
}
I know this doesn't catch every single possible case (I'm still looking for a way to do this). For example, if you enter "3abc", it will take 3 but the rest causes an error. Apparently, it only looks at the first value.
Casting a char as an int is probably one of the better ways to go.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|