Don't use atoi()
and don't use strtol()
. atoi()
has no error checking (as you found out!) and strtol()
has to be error-checked using the global errno
variable, which means you have to set errno
to 0, then call strtol()
, then check errno
again for errors. A better way is to use sscanf()
, which also lets you parse any primitive type from a string, not just an integer, and it lets you read fancy formats (like hex).
For example, to parse integer "1435" from a string:
if (sscanf (argv[1], "%i", &intvar) != 1) {
fprintf(stderr, "error - not an integer");
}
To parse a single character 'Z' from a string
if (sscanf (argv[1], "%c", &charvar)!=1) {
fprintf(stderr, "error - not a char");
}
To parse a float "3.1459" from a string
if (sscanf (argv[1], "%f", &floatvar)!=1) {
fprintf(stderr, "error - not a float");
}
To parse a large unsigned hexadecimal integer "0x332561" from a string
if (sscanf (argv[1], "%xu", &uintvar)!=1) {
fprintf(stderr, "error - not a hex integer");
}
If you need more error-handling than that, use a regex library.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…