Heh, and I hadn't realised that gcc had this sneaky addition over the standard.
Code:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
int main(void)
{
int nr, items;
char ch;
printf("%d\n",INT_MAX);
printf("%lld\n",LLONG_MAX);
while (1)
{
char buf[30];
printf("Enter number: ");
fgets(buf, sizeof(buf), stdin);
errno = 0;
items = sscanf(buf, "%d%c", &nr, &ch);
if (items == 2 && ch == '\n')
if (errno != 0)
perror("Number out of range, try again");
else
break;
else
puts("Not a number, try again");
if (buf[strlen(buf) - 1] != '\n')
while ((ch = getchar()) != '\n' && ch != EOF)
;
}
printf("The number is %d\n", nr);
return 0;
}
However, it seems to be almost completely useless.
Code:
$ ./a.out
2147483647
9223372036854775807
Enter number: 2147483648
The number is -2147483648
$ ./a.out
2147483647
9223372036854775807
Enter number: 9223372036854775808
Number out of range, try again: Numerical result out of range
Enter number: 9223372036854775807
The number is -1
It only seems to generate ERANGE if the number input exceeds the limits of long long int, regardless of the width of the datatype being converted at the moment.
If you have to read your data into the longest data type, then manually check the range to see if will fit in a smaller int, then you may as well use strtol() from the outset. It's the same PITA either way.