[英]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.