在的fscanf和EOF否定扫描集 [英] Negated scanset in fscanf and EOF

查看:131
本文介绍了在的fscanf和EOF否定扫描集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的文件中的逗号分隔字符串列表:

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

名称1,名称2,名称3,

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;
    }

    //...
}

然而,它总是执行比它应该一次。给定的文件中3名,该循环将执行其声明的4倍。这究竟是为什么?是否EOF指标排名对我否定扫描集的 [^] ?如果是这样,那我怎么才能解决这个问题呢?

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?

推荐答案

我是pretty肯定,这是做正是你想要什么。唯一的修改对算法我提出在添加格式字符串的前导空格清楚之前,。另外,我修改了这个开在命令行参数的文件。更容易测试的方式。希望多数民众赞成确定。

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;
}

输出

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.

这篇关于在的fscanf和EOF否定扫描集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆