如何使用fscanf使用分隔符读取文件?

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

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

    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);
    }
}
c file scanf delimiter
1个回答
0
投票

您的代码有效(只要我在调用它之前对定义进行重新排序以定义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,它将与您提供的输入一起运行。因此,要么您的输入错误,您已省略代码,否则您遇到了其他一些问题,这些问题掩盖了缺少最小的,可复制的示例。

© www.soinside.com 2019 - 2024. All rights reserved.