...
| Code Block |
|---|
int si;
if (argc > 1) {
si = atoi(argv[1]);
}
|
The atoi(), atol(), and atoll() functions convert the initial portion of astring pointed to int, long int, and long long int representation, respectively. Except for the behavior on error, they are equivalent to
...
The following compliant example uses strtol() to input an integer value and provides error checking to make sure that the value is a valid integer in the range of int.
| Code Block |
|---|
char buff [25]long sl; int si; char *end_ptr; long long_var; int int_var; fgets(buff, sizeof buff, stdin); if (argc > 1) { errno = 0; long_var sl = strtol(buffargv[1], &end_ptr, 0); if (ERANGE == errno) { puts("number out of range\n"); } else if (long_varsl > INT_MAX) { printf("%ld too large!\n", long_varsl); } else if (long_varsl < INT_MIN) { printf("%ld too small!\n", long_varsl); } else if (end_ptr == buffargv[1]) { printfputs("not validinvalid numeric input\n"); } else { int_varsi = (int)long_var;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.
...