代码之家  ›  专栏  ›  技术社区  ›  homeGrown

strtol未按预期工作[关闭]

  •  -2
  • homeGrown  · 技术社区  · 8 年前

    我无法使用strtol将字符串转换为long。具有领先优势 "." 在字符串中的数字返回0之前。 没有 “,” strtol返回 3456 正如所料。

    #include <stdio.h>                                                              
    #include <stdlib.h>   
    
    int main ()
    {                                                                   
        char str[20] = " . 3456\r\n";                                                                    
    
        long ret = strtol(str, NULL, 10);                                            
        printf("ret is %ld\n",ret);
    
        return(0);                                                                   
    }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   zwol    8 年前

    这个 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;
    }
    
    推荐文章