I have a 3 values (seperated by spaces) in a file that I'm reading into 3 variables using fscanf. For some reason, the values aren't being changed. When I print the values, it prints memory garbage/whatever I set their initial value to. I've tried using fgets with sscanf as well, but no dice.
The code:
int numPresale; // The number of presale tickets sold
double costPresale; // The cost of presale tickets
double costDoor; // The cost of tickets sold at the door
// Opens the file. Exits program if it can't
if((inFile = fopen(fileName, "r")) == NULL) {
printf("Unable to open the input file '%s'\n", fileName);
exit(EXIT_FAILURE);
}
// Parse for information
fscanf(inFile, "%.2f %.2f %d", &costPresale, &costDoor, &numPresale);
printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
fclose(inFile);
I'm sure I'm committing some classic rookie mistake, but I can't find any answers on the web. Thanks in advance for your help!
The reason the values do not change is that the fscanf
does not find values that match the format that you specify. In addition, spaces are not required. Finally, since you are reading the data into double
, not float
, you should use %lf
as the format specifier.
You can check that the proper number of items has been received by checking the return value of fscanf
.
This should fix this problem:
if (fscanf(inFile, "%lf%lf%d", &costPresale, &costDoor, &numPresale) == 3) {
printf("%.2f %.2f %d", costPresale, costDoor, numPresale);
}