【问题标题】:How to read file with delimiters using fscanf?如何使用 fscanf 读取带分隔符的文件?
【发布时间】:2019-11-14 18:50:05
【问题描述】:

我正在尝试读取文件并将信息存储到以下缓冲区

    char bookCode[MAX];
    char title [MAX];
    char author [MAX];
    char year [MAX];
    float selfCost;
    float selfPrice;

我的文件数据是这样的

1738|Jane Eyre|Charlotte Bronte|1997|2.5|4.09
2743|The Kite Runner|Khaled Hosseini|2018|6.32|8.9
6472|Memoirs of a Geisha|Arthur Golden|2011|4.21|6.61
7263|The Divine Comedy|Dante|2009|5.59|7.98
3547|Outlander|Diana Gabaldon|1996|10.99|12.07

目前,我已经尝试了以下

while (fscanf(fi, "%[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)

但它只读取一行然后停止。有什么建议吗?

代码

#include <stdio.h>
#include <stdlib.h>
#define INPUT "HW2_file1.txt"
#define MAX 1000 

int main(void)
{

    FILE *fi = fopen(INPUT, "r");
    if (fi!=NULL)
    {
        printf ("Input file is opened sucesfully\n");
    }
    else
    {
        perror ("Error opening the file: \n");
        exit(1);
    }
    ReadingData(fi);

    fclose(fi);
    return 0;
}
void ReadingData (FILE *fi)
{
    int i=0;
    char bookCode[MAX];
    char title [MAX];
    char author [MAX];
    char year [MAX];
    float selfCost;
    float selfPrice;
    while (fscanf(fi, " %[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)
    {

        printf ("%s %s %s %s %.2f %.2f\n",bookCode,title,author,year,selfCost,selfPrice);
        i++;
        printf ("%d\n",i);
    }
}

【问题讨论】:

  • @user3121023 #define MAX 30
  • 在其周围放置了一个 C 包装器,无法重现。请发布显示问题的Minimal Reproducible Example。请注意,每个bookCode 都将以换行符开头,第一个除外。您可以通过在第一个 % 之前添加一个空格来过滤掉它,如 fscanf(fi, " %[^|]...
  • @WeatherVane 抱歉,我不明白还需要什么,因为我发布了复制所需的所有内容(打开文件的部分除外)
  • 可以复制/粘贴、编译和运行显示问题的 MRE,这样我就可以遇到同样的错误。您尚未发布显示故障的部分。正如评论的那样,我尝试使用您发布的代码,但它并没有“在第一行之后停止”。所以我不得不猜测这可能与存在的流浪换行符有关。
  • 对不起:“您没有发布显示故障的部分”是指代码完整代码。我已经 两次 说过您发布的代码会运行。我们需要生成屏幕截图的代码(使用与您发布的不同的数据)。

标签: c file scanf delimiter


【解决方案1】:

您的代码有效(只要我在调用它之前重新排序定义以定义ReadingData,添加必要的#include#define MAX,并简化它以摆脱未使用的data 类型;我也压缩变量声明以尝试使 TIO 链接适合注释,但最终是徒劳的):

#include <stdio.h>

#define MAX 256

void ReadingData (FILE *fi)
{
    int i=0;
    char bookCode[MAX], title[MAX], author[MAX], year[MAX];
    float selfCost, selfPrice;
    while (fscanf(fi, " %[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)
    {

        printf ("%s %s %s %s %.2f %.2f\n",bookCode,title,author,year,selfCost,selfPrice);
        i++;
        printf ("%d\n",i);
    }
}

int main(void)
{
    ReadingData(stdin);

    return 0;
}

Click this Try it online! link 并且它会根据您提供的输入正常运行。因此,要么您的输入错误,要么您遗漏了代码,要么您遇到了一些其他问题,缺少一个最小的、可重现的示例是隐藏的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多