gpt4 book ai didi

c - 如何使用 fscanf 读取文件中的数据

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:34 25 4
gpt4 key购买 nike

我在一个文件中有一个表格格式。我想使用 fscanf 打印它。该表看起来像这样,有 6 列和 4 行。

Name       Date          Opening    Amount     Type             Closing
Thiluxan 21.05.2015 8500 4500 Withdrawal 4000
Black 05.02.2014 7896 6548 Withdrawal 1348
Whitee 02.05.2015 8524 256394 Deposit 264918
FILE *file1;
file1 = fopen("Bank.txt","r");
while(fscanf(file1, "%s %s %s %s %s %s", text) != EOF ) {
printf("%s\n", text);
}
fclose(file1);

输出不显示任何内容,并返回一个空白屏幕

最佳答案

正如上面的回答和评论中所指出的,您需要在 fscanf 参数中提供六个变量。如果你有一个数据模型也会更好。我建议使用 struct 并将所有数据输入到 structs 数组中,这样您就可以更好地管理它而不是管理随机变量。

#include <stdio.h>

typedef struct Bank {
char name[100];
char date[100];
char opening[100];
char amount[100];
char type[100];
char closing[100];
} Bank;

int main() {
FILE *file1;
file1 = fopen("Bank.txt","r");

Bank bankList[100];
int nCustomers = 0;
while(fscanf(file1, "%s%s%s%s%s%s", bankList[nCustomers].name, bankList[nCustomers].date, bankList[nCustomers].opening, bankList[nCustomers].amount, bankList[nCustomers].type, bankList[nCustomers].closing) != EOF ){
printf("%s %s %s\n", bankList[nCustomers].name, bankList[nCustomers].date, bankList[nCustomers].opening);
nCustomers++;
}
fclose(file1);
}

关于c - 如何使用 fscanf 读取文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com