convert a number from the command line to an integer using strtol
[Found many strtol()
posts, yet not a direct good C answer to OP's question on SO.]
Good strtol()
usage involves base, errno
and the end pointer and testing for various outcomes.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char *argv[]) {
for (int a = 1; a < argc; a++) { // check command line arguments after argv[0].
int base = 10; // convert strings as encoded with decimal digits.
char *endptr; // location to store the end of conversion.
errno = 0;
long val = strtol(argv[a], &endptr, base);
printf("<%s> --> %ld:", argv[a], val);
if (argv[a] == endptr) {
printf(" No conversion.
");
} else if (errno == ERANGE) { // ***
printf(" Out of `long` range.
");
} else if (errno) {
printf(" Implementation specific error %d detected.
", errno);
} else if (*endptr) {
printf(" Trailing junk <%s> after the numeric part.
", endptr);
} else {
printf(" Success.
");
}
}
}
*** Better code uses the value of errno
promptly after strtol()
to insure it reflects an error due to strtol()
and not some later function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…