Question

1 (0.000000,0.000000)   1  429
2 (0.000000,0.000000)   4  58 346 373 465
3 (0.000000,0.000000)   5  94 293 381 431 481
4 (0.000000,0.000000)   3  27 363 458
5 (0.000000,0.000000)   1  471
6 (0.000000,0.000000)   1  79
7 (0.000000,0.000000)   3  111 254 297
8 (0.000000,0.000000)   3  257 425 432
9 (0.000000,0.000000)   2  195 357
10 (0.000000,0.000000)   2  24 95

This is the type of data i am trying to read from file named xyz.txt so i have written some code but still unable to read the file correctly because of the data in discrete format in each line.

#include<conio.h>
#include<stdio.h>

int main() 

{
    FILE *fp;


    struct net 
    { 

      int id,pc;
      float h,w; 
      int a[10];

    }n;



    fp = fopen("xyz.txt","r+");

        if(fp == NULL)
       {
              printf("Error in opening file");
              exit();
       }
       while(fscanf(fp,"%d   (%f ,%f)  %d\n",&n.id,&n.h,&n.w,&n.pc)!=EOF)
     printf("%d (%f ,%f) %d\n",n.id,n.h,n.w,n.pc);


    fclose(fp);
    getch();
     return 0;

}
Était-ce utile?

La solution

Since you're not consuming the whole line with your fscanf, the remaining values trip up your scan. Either use fgets to read the whole line and then scan if with sscanf, or add %*[^\n] to the end of your fscanf (which reads characters until it encounters a newline character, and due to the asterisk, ignores those characters).

Also, you should test fscanf's return value against the number of expected fields, which in your case is 4.

while (fscanf(fp,"%d   (%f ,%f)  %d%*[^\n]", &n.id, &n.h, &n.w, &n.pc) == 4)
    printf("%d (%f ,%f) %d\n", n.id, n.h, n.w, n.pc);

Autres conseils

while(fscanf(fp, "%d (%f,%f) %d",&n.id,&n.h,&n.w,&n.pc)!=EOF){
    int i;
    for(i=0;i<n.pc;++i){
        fscanf(fp, "%d", &n.a[i]);
    }
    printf("%d (%f, %f) %d\n",n.id,n.h,n.w,n.pc);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top