[英]How to read data in a file using fscanf
我在文件中有表格格式。 我想使用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);
}
您的错误是传递给fscanf
的变量数量。 如果要读取6个字符串,则需要提供6个字符串变量以保存在
像这样
FILE * file1;
file1 = fopen("Bank.txt", "r");
while (fscanf(file1, "%s %s %s %s %s %s", t1, t2, t3, t4, t5, t6) != EOF) {
printf("%s %s %s %s %s %s\n", t1, t2, t3, t4, t5, t6);
}
fclose(file1);
当然,您必须实例化所有t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.