+ 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
5 Respuestas
+ 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;
}
+ 3
Ah, this post is very old xD
@Shmuel yes, thank you for pointing that out! Fixed.
+ 1
check whether it ansci code.there is some range for character.and another range for symbols.you can check from there
+ 1
Cohen Creber, I believe line 2 of your code was meant to be "if (x >= 10 && x <= 20)", wasn't it?
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.