+ 1

How do you check if the user has entered valid integer ? For example if the user types in a charecter or a string or an integer greater than the max bound of the integer type.

Valid user integer input

22nd Jul 2016, 10:01 PM
Vladislav Vulchev
Vladislav Vulchev - avatar
5 ответов
+ 7
Use data types like int, float and double to ensure that the user can only enter numerical values. If they don't, then errors will just be thrown which you can choose to catch, send an error, and end the program (or just let it crash). In your case you want integers so of course just use int. As for the boundaries: //if user inputs value between 10 and 20 if (x >= 10 && x <= 20) { //code } else { //error code - out of bounds return 0; }
23rd Jul 2016, 12:24 AM
Cohen Creber
Cohen Creber - avatar
+ 3
Ah, this post is very old xD @Shmuel yes, thank you for pointing that out! Fixed.
3rd Dec 2016, 7:21 PM
Cohen Creber
Cohen Creber - avatar
+ 1
check whether it ansci code.there is some range for character.and another range for symbols.you can check from there
25th Nov 2016, 6:04 PM
Adnan Aatif
Adnan Aatif - avatar
+ 1
Cohen Creber, I believe line 2 of your code was meant to be "if (x >= 10 && x <= 20)", wasn't it?
3rd Dec 2016, 7:19 PM
Shmuel
Shmuel - avatar
0
for specifying ranges, your prompt for input can explicitly state said range. you can still back it up by code like this one asking for negative number: //variable a should be negative do{ cout<<"Enter a negative number.\n"; cin>>a; }while (a>=0); /* The exit control loop executes at least once and is thus ideal for preventing errors. */ there's always the classic 'if-else' and 'throw-catch' methods, but here's some cases where data type modifiers are really helpful: if you think that input may be large, declare variables using 'long' prefix. for restricting input to positive values only - 'unsigned' data type can be used.
25th Dec 2016, 9:19 AM
Nathan Algren