—This is a Homework question—
I’m having problems reading float values from a text file using fscanf.
Basically I’m trying to read float values from a file and store them in a dynamic array.
The input file has two floats per line. so a line might be “0.85 7.34” (w/o quotes). so I’m trying to use fscanf(fp, “%f %f”, &coordinates[i], &coordinates[i++]) to read in the 2 float values. when i print it shows as 0.00000. Below is the code I wrote and the output it produces.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv []) {
FILE * fp = fopen("nums", "r");
float *coordinates;
float *tmp;
int i = 0;
int ARRAY_SIZE = 5;
coordinates = malloc(5*sizeof(float));
while (fscanf(fp,"%f %f", &coordinates[i], &coordinates[i++]) > 1)
{
printf("iteration# %d | coord1 = %f coord2 = %f \n", i, &coordinates[i-1], &coordinates[i]);
if (i >= ARRAY_SIZE)
{
tmp = realloc(coordinates, (i*2)*sizeof(float));
coordinates = tmp;
ARRAY_SIZE = i*2;
}
i++;
}
for(i = 0; i < 8; i++)
printf("%f\n", &coordinates[i]);
return 0;
}
OUTPUT:
iteration# 1 | coord1 = 0.000000 coord2 = 0.000000
iteration# 3 | coord1 = 0.000000 coord2 = 0.000000
iteration# 5 | coord1 = 0.000000 coord2 = 0.000000
iteration# 7 | coord1 = 0.000000 coord2 = 0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
You don’t use the “address of”-operator
&withprintf.fscanfrequires a pointer to the data so it knows can change the variables value, while printf does not.Change:
To: