Negated scanset in fscanf and EOF

2019-07-17 21:08发布

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?

2条回答
虎瘦雄心在
2楼-- · 2019-07-17 21:30

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-17 21:48

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.

查看更多
登录 后发表回答