这个
strto*
库函数将只跳过前导空格。如果你想跳过其他文字,你需要手动完成。这个
isxxx
功能来自
ctype.h
可以帮助:
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv)
{
char *p, *endp;
unsigned long ret;
int fail = 1;
if (argc != 2) {
fprintf(stderr, "usage: %s number-to-parse\n", argv[0]);
return 2;
}
p = argv[1];
while (*p && !isdigit(*p)) p++;
errno = 0;
ret = strtoul(p, &endp, 10);
if (endp == p)
printf("'%s': no number found\n", str);
else if (*endp && !isspace(*endp))
printf("'%s': junk on line after number\n", str);
else if (errno)
printf("'%s': %s\n", str, strerror(errno));
else {
printf("'%s': parsed as %lu\n", str, ret);
fail = 0;
}
return fail;
}