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.
wallyk
source share