Fscanf not reading floats from file properly into linked list

So basically, using C, I'm trying to read information from a file into a linked list and I had this working when only the price was a float and size was a string but I need to read the size also as float. I'm reading the file like this

fscanf(file,"%[^-]-%f[^:]:%f\n", pLog->name, &pLog->size, &pLog->price);

and the file's structure is like this


Now when I try to check the results with

printf("%s %.2f %.2f\n", pLog->name, pLog->size, pLog->price);

It prints everything like this

bottle 0.33 8290796282473829.00
bottle 0.50 2572489705689592000000000000000000000000000000000000000.00
bottle 1.50 0.00

Anybody have a clue what's going wrong?


Code used wrong format @BLUEPIXY

// bottle-0.33:0.10
fscanf(file,"%[^-]-%f[^:]:%f\n", pLog->name, &pLog->size, &pLog->price);

"%[^-]" matches "bottle" and saves text in pLog->name.
"-" matches "-" and scanning continues.
"%f" matches "0.33" and saves the value 0.33 in pLog->size.
"[" does not matches ":", so scanning stops, function returns a 2.
Remaining format "^:]:%f\n" is not relevant.

Use correct format, width limit and check result.

// assume sizeof pLog->name is 10
if (fscanf(file,"%9[^-]-%f:%f\n", pLog->name, &pLog->size, &pLog->price) == 3) 

You forgot to check the return value of fscanf. Otherwise it would be quite obvious what has happened.

Always check the return value of functions you call.

You're making a mistake there by passing the pointers to the printf() call, too.

  printf("%s %.2f %.2f\n", pLog->name, &pLog->size, &pLog->price);

should be

 printf("%s %.2f %.2f\n", pLog->name, pLog->size, pLog->price);
                                     ^^^         ^^^ 

FWIW, supplying mismatched argument to the format specifier invokes undefined behavior.

Also, to match an input like "bottle-0.33:0.10", a format specifier like "%[^-]-%f:%f" would also suffice.

That said, it's always required to check the return value of scanf() and family calls so as to verify the success. Otherwise, you'll probably end up using some uninitialized value, which may again lead to UB.


 ? Reading float numbers from a file in a special manner
 ? How to read from a file using fgets?
 ? strange crash on fscanf
 ? Confusing Format Error C Program fscanf
 ? Why MSB's are discarded during 2's complement multiplication?
 ? Why MSB's are discarded during 2's complement multiplication?
 ? Why MSB's are discarded during 2's complement multiplication?
 ? Why are signed and unsigned multiplication different instructions on x86(-64)?
 ? Why Two's Complement?
 ? Is booth multiplication algorithm for multiplying 2 positive numbers?