0

I have a table format in a file. I want to print it using fscanf. The table looks like this with 6 columns and 4 rows.

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

Padmal
  • 458
  • 5
  • 15

2 Answers2

2

As pointed out in answer and comments above, you need to provide six variables into the fscanf arguments. 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.

#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);
}
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
1

Your mistake is the number of variables you passed into fscanf. If you want to read 6 strings you need to provide 6 string variables to save in

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 ts of course

Issam Rafihi
  • 432
  • 3
  • 10
  • 1
    In addition to that, it would be a good idea to check the return value of `fopen` as well as ensuring that the return value of `fscanf` is the expected number of arguments, instead of just checking it is not `EOF`. – Hulk Jul 31 '19 at 05:48