Check maximum number in scanf

I want to read int from stdin, but I want to check if the user is greater than int max. How can i do this?

int n; scanf("%d", &n); 

scanf reads the decimal input and stores it in int, causing an overflow. How can I check and avoid this?

+6
c scanf
source share
4 answers

The only way to convert the string representation of a number to the actual value and observe the overflow is to use functions from the strto.. group. In your case, you need to read the string representation of the number, and then convert it using the strtol function.

Beware of answers that suggest using atoi or sscanf to perform the final conversion. None of these features protect against overflow.

+10
source share

Another way is to set max. digits for parsing.

For example:

  int n; scanf("%5d", &n); // read at most 5 digits printf("%i\n", n); 
+1
source share

Two methods come to mind.

The first is useful if you know that the input is integer as soon as the input, but suffers from "slightly" exceeding the integer range:

 long x; if (1 != scanf("%ld", &x)) error "not a number or other i/o error" else if (x < -MAXINT || x > MAXINT) error "exceeds integer range" else printf "it is an integer"; 

It is highly dependent on the compiler and platform. Note that the C language only guarantees that long greater than or equal to the size of int . If this is done on a platform where long and int are the same size, this is a futile approach.

The second approach is to read the input as a string and parse directly:

 char buf [1000]; if (1 != scanf ("%1000s", buf)) error "i/o error"; size_t len = strspn (buf, "0123456789+-"); if (len != strlen (buf)) error "contains invalid characters"; long number = 0; int sign = 1; for (char *bp = buf; *bp; ++bp) { if (*bp == '-') { sign = -sign; continue; } if (*bp == '+') continue; number = number * 10 + *bp - '0'; if (number > MAXINT) error "number too large"; } if (sign < 0) number = -number; 

This code has several drawbacks: it depends on long more than int ; it allows you to see plus and minus anywhere on the line. It could be easily expanded to allow others other than the base ten numbers.

A possible third approach would be to enter a character set validation string and use the double conversion to validate the range.

0
source share

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

-one
source share

All Articles