fscanf not breaking fully spliting a file

Viewed 41

I'm trying to read a file in a comma separated value format, the program reads the first two data types and fails to read the last. Please can I have some help

Here's what's in the file I'm trying to read:

Jane,50,400.60

Here's the code:

    FILE* fptr;
    char fileContent[1000];

    char name[100];
    int age = 0;
    double bBalance = 0;

    fptr = fopen("NTD.txt", "r");

    if (fptr == NULL)
    {

    }
    else
    {
        while (fscanf(fptr, "%30[^ ,], %d[^ ,], %lf[^ ,]",
                             &name, &age, &bBalance) != NULL)
        {
            printf("---------------- \n");
            printf("NAME: %s \n", name);
            printf("AGE: %d \n", age);
            printf("BANK BALANCE: %lf \n", bBalance);
        }
    }

This is what the program is supposed to output:

----------------
NAME: Jane
AGE: 50
BANK BALANCE: 400.600000

This is what the program actually outputs:

----------------
NAME: Jane
AGE: 50
BANK BALANCE: 0.000000

Can anyone please tell me what I'm doing wrong here?

If you need anything else please comment below.

1 Answers

In %d[^ ,], %d matches a decimal numeral, and then [ seeks a literal [ character, but there is none in the input, so fscanf stops.

You may need to use fscanf for only one decimal numeral at a time and write additional code to check the characters in between them.

Related