Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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