[英]How to read data in a file using fscanf
I have a table format in a file. 我在文件中有表格格式。 I want to print it using fscanf.
我想使用fscanf打印它。 The table looks like this with 6 columns and 4 rows.
该表看起来像这样,有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);
The output doesn't show anything and it returns a blank screen 输出不显示任何内容,并且返回黑屏
As pointed out in answer and comments above, you need to provide six variables into the fscanf arguments. 如以上答案和注释中所指出的,您需要在fscanf参数中提供六个变量。 Also it would be better if you have a model for your data.
如果您有一个数据模型,那就更好了。 I would suggest to use a
struct
and input all data into an array of structs
, that way you would be able to manage it better rather than managing random variables. 我建议使用一个
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);
}
Your mistake is the number of variables you passed into fscanf
. 您的错误是传递给
fscanf
的变量数量。 If you want to read 6 strings you need to provide 6 string variables to save in 如果要读取6个字符串,则需要提供6个字符串变量以保存在
Like So 像这样
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);
You have to instantiate all t
s of course 当然,您必须实例化所有
t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.