fgets() to read a line of input.
strtol() to validate, convert and check for numeric overflow.
Both provide some success/fail indication in their status returns.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
If cin fails to read the type it expects, it will enter an error state and won't accept further input. Try this:
while (n<1||n>10)
{
cout << "\nInvalid input. Try again (1..10) -> ";
cin.clear();
cin >> n;
cin.ignore(SHRT_MAX, '\n');
}
Also, you need to initialize n to something. If the first input fails, n will remain indeterminate, and that could cause a number of problems.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
As long as it's something outside of your valid range, it doesn't matter what value you choose.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>I didn't work!!!
Not helpful. Post the code that doesn't work and explain how it doesn't do what you want.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401