C:使用strtol endptr永远不会为NULL,不能检查值是否只是整数?

时间:2013-09-23 22:54:43

标签: c++ c strtok strtol

所以这就是问题所在。我有一组应该是的数据:

int 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");
                    }
            }

谢谢!

1 个答案:

答案 0 :(得分:5)

假设早期代码已经将该行拆分为单个数字,那么您想要的检查是

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 */;