Strtol没有返回正确的endptr-C

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

例如,我在文本文件中包含以下行:1 abc

例如,这是无效的行,因为此特定行必须包含一个且只有一个整数值。

现在,当我以这种方式使用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”。

w910488011 回答:Strtol没有返回正确的endptr-C

"1 abc"跳过空格。因此,如果您有输入fscanf(fs,"%s",lineInput); 并使用

进行扫描
lineInput

"1"的内容最终为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; }

{{1}}
本文链接:https://www.f2er.com/3084780.html

大家都在问