This is the code (located inside a function) that opens a file and then reads its content with fscanf():
FILE *file = NULL;
int xTemp = 0, xTot = 0;
int yTemp = 0, yTot = 0;
int zTemp = 0, zTot = 0;
int i = 0;
file = fopen(nomeFile, "r");
if(file == NULL) {
return 0;
} else {
while(!feof(file)) {
if(fscanf(file, "%f %f %f", &xTemp, &yTemp, &zTemp) != 3) {
return -1;
} else {
i++;
xTot += xTemp;
yTot += yTemp;
zTot += zTemp;
}
}
coords.x = xTot/i;
coords.y = yTot/i;
coords.z = zTot/i;
return i;
}
And this is the content of the file i’m reading using fscanf():
3.5 2.1 -1.4
4.1 -4.1 2.9
2.6 2.5 3.2
-1.2 0.0 4.3
1.5 1.3 6.0
The problem is that fscanf() won’t assign to xTemp, yTemp and zTemp the proper values.
Use float variables instead of
ints. Infscanfyou are using%fbut the variables are ints which invokes undefined behaviour.