繁体   English   中英

Strtol 没有返回正确的 endptr - C

[英]Strtol doesn't return the correct endptr - C

我必须从文件行中解析数据,为此我现在使用 strtol() function。

例如,我在文本文件中有这一行:1 abc

例如,这是一个无效行,因为此特定行必须包含一个且仅一个 integer 值。

现在,当我以这种方式使用 strtol 时:

    FILE *fs;
    fs = fopen("file.txt", "r");
    char* ptr = NULL; // In case we have string except for the amount
    char lineInput[1024]; // The max line size is 1024
    fscanf(fs, "%s", lineInput);
    long numberOfVer = strtol(lineInput, &ptr, BASE);
    printf("%lu\n%s\n", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
    if (numberOfVer == 0 || *ptr != '\0') { // Not a positive number or there exists something after the amount!
        fprintf(stderr, INVALID_IN);
        return EXIT_FAILURE;
    }

但是,ptr 字符串不是“abc”或“abc”,它是一个空字符串……这是为什么呢? 根据文档,它必须是“abc”。

scanf("%s")跳过空格。 因此,如果您输入"1 abc"并使用

fscanf(fs, "%s", lineInput);

lineInput内容最终为"1" ,字符串的 rest 留在输入缓冲区中,为下一次输入操作做好准备。

通常用于读取行的 function 是fgets()

    FILE *fs;
    fs = fopen("file.txt", "r");
    char* ptr = NULL; // In case we have string except for the amount
    char lineInput[1024]; // The max line size is 1024
    // using fgets rather than fscanf
    fgets(lineInput, sizeof lineInput, fs);
    long numberOfVer = strtol(lineInput, &ptr, BASE);
    printf("%ld\n%s\n", numberOfVer, ptr); // Here I test the values, I expect to get 1 followed by newline and abc
    //      ^^^ numberOfVer is signed
    if (numberOfVer == 0 || *ptr != '\0') { // Not a positive number or there exists something after the amount!
        fprintf(stderr, INVALID_IN);
        return EXIT_FAILURE;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM