How do I modify this code?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
enum { INPUT_SIZE = 30 };
int main () {
char *ptr;
long ret;
char str[INPUT_SIZE];
fgets(str, INPUT_SIZE, stdin);
ret = strtol(str, &ptr, 10);
if( ret == LONG_MAX || ret == LONG_MIN ) {
perror("!! Problem is -> ");
}
else if (ret) {
printf("The number is %ld\n", ret);
}
else {
printf("No number found input is -> %s\n", ptr);
}
return(0);
}
If successful, strtol()
returns the converted long int value.
If unsuccessful, strtol()
returns 0
if no conversion could be
performed. If the correct value is outside the range of representable
values, strtol()
returns LONG_MAX
or LONG_MIN
, according to the sign
of the value. If the value of base is not supported, strtol()
returns 0
.
If unsuccessful strtol()
sets errno to one of the following values:
Error Codes:
EINVAL The value of base is not supported.
ERANGE The conversion caused an overflow.
Source : IBM
Can you check overflow using scanf()
for example?
Input: 1234 stackoverflow
Output: The number is 1234
Input: 123nowhitespace
Output: The number is 123
Input: number is 123
Output: No number found input is -> number is 123
Input: between123between
Output: No number found input is -> between23between
Input: 9999999999999999999
Output: !! Problem is -> : Result too large
Maybe off-topic but, Jonathan Leffler says in his comments(in another topics) that handle warnings just as errors.