Negated scanset in fscanf and EOF

谁都会走 提交于 2020-01-24 17:54:49

问题


I've got a comma-separated list of strings in my file:

Name 1, Name 2, Name 3,

I want to read those names skipping all commas. I've written the following loop:

while(true)
{
    if(fscanf(file, "%[^,],", my_string) != 1)
    {
        break;
    }

    //...
}

However, it is always executing one more time than it supposed to. Given 3 names in the file, the loop will execute its statements 4 times. Why is this happening? Does EOF indicator rank to my negated scanset [^,]? If so, then how can I solve this issue?


回答1:


I'm pretty sure this is doing exactly what you want it to. The only modification to the algorithm I made is added the leading whitespace-clear before the % in the format string. Also,I modified this to open the file from a command-line arg. Easier to test that way. Hope thats ok.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
        return EXIT_FAILURE;

    FILE *fp = fopen(argv[1], "r");
    if (NULL == fp)
        return EXIT_FAILURE;

    char str[100];
    int count=0;
    while (1)
    {
        if(fscanf(fp, " %[^,],", str) != 1)
            break;
        printf("%s\n", str);
        ++count;
    }

    printf("Parsed %d strings.", count);
    return EXIT_SUCCESS;
}

Output

Name 1
Name 2
Name 3
Parsed 3 strings.

I believe the "fourth" execution in the loop you're seeing is the failure condition, which breaks the loop due to failure to parse, unless I'm missing something or not understanding what you're witnessing.




回答2:


Why are your loop statements executing 4 times. The loop breaks after 4th fscanf statement and codes below aren't executed.EOF indicator doesn't rank to your negated set However maybe you are looking for a more compact solution like this:

while(fscanf(file, "%[^,],", my_string)!=EOF )
    {

        //do something
    }

If not, please post more detailed code and your test file



来源:https://stackoverflow.com/questions/14510715/negated-scanset-in-fscanf-and-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!