tags:

views:

303

answers:

3

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?

A: 

Read it into a string and check the length, then call either atol() or sscanf() on the string to convert it into a int.

Martin Beckett
Not `atoi` and not `sscanf`. Neither of these protect from overflow. "Checking the length" cannot be used to prevent overflow for obvious reasons.
AndreyT
you can assume though that if the entered number is 10 digits long it isn't gong to fit into an int.
Martin Beckett
`2000000000` is 10 digits long and it fits into a 32-bit int without a problem.
AndreyT
A: 

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);
Nick D
+5  A: 

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.

AndreyT
Can you show a complete example on how to convert to a long and check the "overflow" error?
AlfaTeK
There's not much to show. In case of overflow `strtol` sets `errno` to `ERANGE`. Just check the value of `errno` to catch overflow.
AndreyT
And that is Ansi C compatible (C89)?
AlfaTeK
Yes, this is now `strtol` (and the rest of `strto...` functions) is described in C89/90.
AndreyT