Search code examples
cstringfilefgetsscanf

Reading a file with different variable types into a structure in c


I'm trying to figure out how to read a file that contains different variable types. In this case the .txt file is formatted like this.

MCD
McDonald's
20.45
BK
Burger King
30.47
DQ
Dairy Queen
25.63

It goes in a pattern of two strings followed by a double. My code to read in the file is as follows

int fillArray(struct Stock * array, FILE * fin)
{
   int i = 0;
   char buff[MAX];
   while(fgets(buff, MAX, fin) != NULL)
   {
       strcpy(array[i].symbol, buff);
       fgets(buff, MAX, fin);
       strcpy(array[i].companyName, buff);
       fscanf(fin, "%lf", &array[i].currentPrice);
       i++;
    }
    return i;
}

When I go to print the structure I get this output.

MCD
McDonald's
20.45
BK
0.00Burger Kin30.47
30.47
0.00DQ
Dairy Queen
25.63

0.00

It seems things fall apart as soon as a string with spaces is read. Does anyone know what might be causing this? Thanks.


Solution

  • After the number is read using

    fscanf(fin, "%lf", &array[i].currentPrice);
    

    the newline character is still there in the input stream. The next call to fgets() reads only the newline into the array.

    Add the following to skip till the end of the line after that.

    int c;
    while ( ( c = fgetc(stdin)) != EOF && c != '\n');