I want to read a int from stdin but I want to validate if the user exceeds the int max value. How can I do it?
int n; scanf("%d", &n);
scanf reads the decimal input and stores in the int, causing overflow. How can I check and avoid this?
I want to read a int from stdin but I want to validate if the user exceeds the int max value. How can I do it?
int n; scanf("%d", &n);
scanf reads the decimal input and stores in the int, causing overflow. How can I check and avoid this?
Read it into a string and check the length, then call either atol() or sscanf() on the string to convert it into a int.
Another way is to set max digits to parse.
For example:
int n;
scanf("%5d", &n); // read at most 5 digits
printf("%i\n", n);
The only way to convert a string representation of a number to the actual value and to watch for overflow is to use functions from strto..
group. In your case you need to read in a string representation of the number and then convert it using strtol
function.
Beware of responses that suggest using atoi
or sscanf
to perform the final conversion. None of these functions protect from overflow.