I am scanning in an array of doubles from a file. I can print this array to retrieve the correct values for each line in the file.
My problem occurs when I try to scan in another file into another array during this process.
I have:
// // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main (int argc, char **argv) { double c[13], d[13]; char filename[20]; double x1, x2, y1, y2, z1, z2, d1, d2, au, aux, auy; double dx, dy, dz, nnid, chk, nn; int n, b; char *in; in=argv[1]; FILE* infile; FILE* inbfile; infile = fopen(in, "r"); inbfile = fopen("copy.bt", "r"); while (!feof(infile)) { fscanf(infile, "%f %f %e %e %e %e %e %e %e %e %e %e %e %f",c,c+1,c+2,c+3,c+4,c+5,c+6,c+7,c+8,c+9,c+10,c+11,c+12,c+13); printf("Selected Particle A: %f\n",c[0]); n=0; while (!feof(infile)) { printf("%f\n",c[0]); fscanf(infile, "%f %f %e %e %e %e %e %e %e %e %e %e %e %f",d,d+1,d+2,d+3,d+4,d+5,d+6,d+7,d+8,d+9,d+10,d+11,d+12,d+13); printf("%f\n",c[0]); printf("Selected Particle B: %f\n",d[0]); /**/ printf("%f = %f ?\n",c[0],d[0]); if (c[0]==d[0]) { printf("Same Particle SKIP...\n"); } else { dx = (d[4])-(c[4]); dy = (d[5])-(c[5]); dz = (d[6])-(c[6]); printf("dx dy dz %e %e %e\n",d[4],d[5],d[6]); /**/ if (n == 0) { au=pow(((dx*dx*dx)+(dy*dy*dy)+(dz*dz*dz)),(1.0/3.0)); printf("%f is %e from %f\n",c[0],au,d[0]); } else { aux=pow(((dx*dx)+(dy*dy)+(dz*dz)),(1.0/3.0)); printf("%f is %e from %f\n",c[0],aux,d[0]); if (aux < au) { au = aux; nnid = d[0]; } } /**/ } n++; nn=d[1]; /**/ } printf("%f Is Particle %f At %e\n", c[1], nnid, au); } fclose(infile); fclose(inbfile); return 0; } So why does the value change? All I've done is scan in the first line of another file into a separate array.
fscanf()argument lists.feof()in C is after a routine reports failure and you need to distinguish between EOF and a formal error. You should be usingwhile (fscanf(infilea, "...", ...) == 4) { ... while (fscanf(infileb, "...", ...) == 4) { ... } ... }. The 4 is the number of conversions you expect (the number of%eand%flisted in the format strings). Any shortfall indicates a problem; it might be a format error (an alphabetic character where a number was expected), or it might be EOF. After the loop, it would be legitimate to usefeof()to distinguish the cases.