简体   繁体   中英

getting fscanf to store in structs in C

I have an assignment where I need to get Values of RLC circuits from a file and calculate the resonant frequency however my issue is when I use the fscanf function it reads only the first line of the file and the rest comes out as zeros .

#include <stdio.h>
data

 int h;
typedef struct cct
{
  int code[50];
  float R[50];
  float L[50];
  float C[50];
} CCT;

 int read(CCT cct[], int n_p, FILE* fp){
   char temp;

   if(fp==NULL){
       printf("Error\n");
       return -1;
   }
   fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);

}
int main()
{
   FILE* fp = fopen("U://datafile.txt", "rt");
   int i = 0;
   CCT cct[50];
   int size;

   while (!feof(fp)) {
       read(cct, i, fp);
       i++;
   }
   size = i;

   for (i = 0; i < size; ++i)
     printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
            cct[i].L[i], cct[i].C[i]);

 scanf("%d",&h);
   fclose(fp);
}

and this is the data file

    1,4.36,2.23e-2,4.65e-8
    2,4.57,2.01e-2,5.00e-8
    3,3.99,2.46e-2,4.82e-8
    4,4.09,2.60e-2,4.70e-8

I would appreciate if someone could point put why it only gets the first line. Thanks

fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);

Something like the following, perhaps

#include <stdio.h>

typedef struct cct {
  int code;
  float R;
  float L;
  float C;
} CCT;

int h;

int read(CCT cct[], int n_p, FILE* fp){
   char temp;

   if(fp==NULL){
       printf("Error\n");
       return -1;
   }
   fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
   FILE* fp = fopen("U://datafile.txt", "rt");
   int i = 0;
   CCT cct[50];
   int size;

   while (!feof(fp)) {
       read(cct, i, fp);
       i++;
   }
   size = i;

   for (i = 0; i < size; ++i)
     printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
   fclose(fp);
}

CCT is composed of multiple arrays (you have arrays of arrays, which is wrong for the exercise, but that's not the point) and you always write to the element zero of the arrays. For example, cct[n_p].code in fscanf() is the address of the array, which is identical to the address of cct[n_p].code[0]. Then you print code[i] in the output loop, which is blank except for i == 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM