繁体   English   中英

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

[英]Fscanf reads unmatching format from input

我只想从文件中读取符合此格式的行: identifier=any-char-string ,并忽略不对应的行。 此外,我想将标识符放入一个变量中,并将任何字符字符串放入另一个变量中。

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

对于正确的输入,如:“name=string”,它运行良好,但问题是当我引入不匹配的输入时,如:“我回家”,它没有“=”符号,但这一行被解释为正确的。 有什么建议?

你必须在等号的两边加上空格。 否则它将无法区分等号和字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM