Fscanf从输入中读取不匹配的格式

问题描述 投票:0回答:1

我只想从文件中读取遵守此格式的行:identifier = any-char-string,并忽略不对应的行。我也想将identifier放入变量,并将any-char-string放入另一个变量。

我的代码是:if(fscanf(f,"%[^=]=%[^\n]",l.iden,l.string)==2)

对于正确的输入,例如:“ name = string”,它可以很好地工作,但是问题是当我引入不匹配的输入,例如:“ i go home”时,它没有“ =”符号,但此行被解释为正确的。有什么建议吗?

c scanf
1个回答
0
投票

您必须在等号的两侧放置空格。否则它将无法从字符串中区分等号。

#include<stdio.h>
#include<string.h>
int main()
{
    freopen("input.txt", "r", stdin);

    char identifier[100], any_char_str[100];

    while(1)
    {
        int ret_count = scanf("%s = %s", identifier, any_char_str);

        if(ret_count == EOF || ret_count == 0) // If it reaches to the EOF break the loop or if "scanf()" consumes nothing
        {
            break;
        }
        else if(ret_count != 2) // If exactly two strings are not found maintaining this %s = %s pattern ignore it (if more than one '=' is found like a = b = c it will take upto which the pattern is maintained)
        {
            continue;
        }

        printf("%s %s\n", identifier, any_char_str);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.