【问题标题】:Fscanf reads unmatching format from inputfscanf 从输入中读取不匹配的格式
【发布时间】:2020-01-26 09:49:01
【问题描述】:

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

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

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

【问题讨论】:

  • 你使用什么语言?
  • 我使用C语言
  • 将相应的语言添加为不在标题或 cmets 中的标签。
  • fgets()读取,然后使用sscanf(f,"%[^=]=%[^\n]",...

标签: c scanf


【解决方案1】:

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

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

【讨论】:

  • 这不太对。如果 scanf 不消耗任何内容,它将返回 0 并保持文件位置不变,因此循环的每次迭代都尝试从同一个位置开始读取。也许可以提出这样的论点,即格式字符串永远不会发生(事实上,我相信在这种情况下确实如此),但这似乎非常脆弱,如果 scanf 字符串以 %d 开头,这种模式就会中断。您应该包括一个ret_count == 0 案例。此外,对于格式错误的输入,这将不会正确运行 w.r.t。换行符。
  • @William Pursell 谢谢你的建议....我已经修好了。但是我没有正确地得到它会失败的角落案例......请您考虑提供这样的示例输入吗?
  • 考虑像"foo =\nbar = c\n"这样的输入
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多