【问题标题】:How to use fscanf() in C to recognize patterns that are recognized as strings?如何在 C 中使用 fscanf() 来识别被识别为字符串的模式?
【发布时间】:2018-12-14 12:12:49
【问题描述】:

我想使用 fscanf 来识别以下模式:

Product|10|Meter

一种产品,它的数量和计量器。

fscanf() 用作:

fscanf(file, "%s|%d|%s");

我遇到的问题是字符串正在获取所有内容,而其他变量没有收到任何值。

这是我的代码:

while ((fscanf(arqProdTemp, "%s|%d|%s", insumo, qtdInsumos, unidade)) != EOF) {
    printf("%s - %d %s", insumo, qtdInsumos, unidade);
}

当我使用printf() 函数时,insumo 的结果是整个字符串!

【问题讨论】:

  • %s 拾取所有连续的非空白字符。查看%[],例如。 %[^|]
  • 但我要改用那个?我需要三个值。
  • 他建议你使用"%[^|]|%d|%s"。也就是说,将您的第一个 %s 替换为 %[^|]
  • 或者,您可以从fgetsstrtok 之类的东西开始此类任务,而不是fscanf
  • 请注意,您应该使用 while (fscanf(…) == 3) 来确保您读取 3 个值。如果你得到 2、1 或 0,你就会遇到各种格式问题(你当前的模式不太可能返回 0,但一般来说,这是一个选项)。以及表示没有更多数据要读取的 EOF。

标签: c string file formatting scanf


【解决方案1】:

按照 cmets 的建议,您可以这样做

fscanf(arqProdTemp, "%[^|]|%d|%s", insumo, &qtdInsumos, unidade);

请注意,如果qtdInsumos 是一个整数变量,您需要将其地址与&qtdInsumos 一起传递给fscanf()。不是它的价值。

insumounidade 是用于存储字符串的字符数组。确保数组足够大以存储字符串并使用宽度说明符,如

fscanf(arqProdTemp, "%14[^|]|%d|14%s", insumo, &qtdInsumos, unidade);

其中 15 被假定为两个数组的大小。根据需要进行更改。

另外,检查fscanf() 的返回值,看看是否一切顺利。 fscanf() 返回成功分配的数量,在这种情况下必须为 3。

if( fscanf(arqProdTemp, "%[^|]|%d|%s", insumo, &qtdInsumos, unidade) != 3 )    
{
    //Something went wrong
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 2011-04-09
    • 2013-11-10
    • 2020-12-10
    • 2017-02-12
    • 2022-06-16
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多