【问题标题】:C: using strtol endptr is never NULL, cannot check if value is integer only?C:使用 strtol endptr 永远不会为 NULL,不能检查值是否仅为整数?
【发布时间】:2013-09-23 22:54:43
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: c++ c strtok strtol


    【解决方案1】:

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

    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,这意味着你给了@ 987654325@ 空字符串,可能不算作有效数字。 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 */;
    

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多