...
Code Block |
---|
char buff [25]; char *end_ptr; long sl; int si; fgets(buff, sizeof buff, stdin); errno = 0; sl = strtol(buff, &end_ptr, 0); if (ERANGE == errno) { puts("number out of range\n"); } else if (sl > INT_MAX) { printf("%ld too large!\n", sl); } else if (sl < INT_MIN) { printf("%ld too small!\n", sl); } else if (end_ptr == buff) { puts("not valid numeric input\n"); } else if ('\0' != *end_ptr) { puts("extra characters on input line\n"); } else { si = (int)sl; } |
If you are attempting to convert a string to a smaller interger type (int
, short
, or signed char
), then you only need test the result against the limits for that type. The tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.
Note that this solution treats any trailing characters, including white space characters, as an error condition.
References
- Jack Klein. Bullet Proof Integer Input Using strtol(). http://home.att.net/~jackklein/c/code/strtol.html
- ISO/IEC 9899-1999 Section 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions; Section 7.19.6 Formatted input/output functions