[英]C: using strtol endptr is never NULL, cannot check if value is integer only?
所以这就是问题所在。 我有一组应该是的数据:
int int int ....
但是,我希望如果我有1asdas 2,我希望能够抓住“ asdas”部分。 但是,此刻,如果我只有1 2,则endptr不为NULL,因此我无法检查该值是数字还是数字和字母。 这是我的代码:
else if(token != NULL && token2 != NULL && token3 == NULL){
//we POSSIBLY encountered row and column values for the matrix
//convert the two numbers to longs base 10 number
int row = strtol(token, &result, 10);
int col = strtol(token2, &result2, 10);
printf("Result is %s and result2 is %s\n", result, result2);
//check to see if both numbers are valid
//this will be true if there were only 2 digits on the line
if(!result && !result2){
//SUCCESSFULL parsing of row and column
printf("SUCCESSFUL PARSING\n");
}
}
谢谢!
假设先前的代码已经将行拆分为单独的数字,则所需的支票是
errno = 0;
long row = strtol(token, &endtoken, 10);
if (*endtoken != '\0')
fprintf(stderr, "invalid number '%s' (syntax error)\n", token);
else if (endtoken == token)
fprintf(stderr, "invalid number '' (empty string)\n");
else if (errno)
fprintf(stderr, "invalid number '%s' (%s)\n", token, strerror(errno));
else
/* number is valid, proceed */;
strtol
永远不会将endtoken
设置为空指针; 它将设置为指向不是数字的第一个字符 。 如果该字符是NUL 字符串终止符 (请注意略有不同的拼写),则整个字符串都是有效数字, 除非 endtoken == token
,这意味着您给strtol
空字符串,这可能不算作有效字符串数。 errno
操作对于捕获语法上正确但在long
范围之外的数字是必需的。
您可以通过直接将数字从行缓冲区中拉出而不是先将其拆分来简化代码:假设任何给定的行上都应该有两个数字,
char *p = linebuf;
char *endp;
errno = 0;
long row = strtol(p, &endp, 10);
if (endp == p || !isspace(p) || errno)
/* error, abandon parsing */;
p = endp;
long col = strtol(p, &endp, 10);
if (endp == p || p != '\0' || errno)
/* error, abandon parsing */;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.