-4

i'm trying to read a formatted file in C this is a sample line of the file:

SURNAME;NAME;MINUTES'SECONDS''ONE-HUNDREDTHS OF A SECOND

I wrote this code:

 while(!feof(fp))
 {
    fscanf(fp,"%[^;]s",surname);
    fscanf(fp,"%c",&c);
    fscanf(fp,"%[^;]s",name);
    fscanf(fp,"%c",&c);
    fscanf(fp,"%d'%d''%d",&min,&sec,&sec_cent);
    fscanf(fp,"\n");
}

It works well with the name and surname strings, but it doesn't extract the time MINUTES'SECONDS''ONE-HUNDREDTHS OF A SECOND and i don't know why

Can someone help me?

1 Answers1

3

There are a couple of things you may want to change in your code:

  • Always check the return value of scanf (or fscanf) to see if all the data were read.
  • Don't use feof() to control a loop.
  • You don't need to extract the '\n' with scanf, unless you are going to use getline() afterwards.
  • You don't need the s too, with that format specifier, but you should prevent buffer overflows limiting the number of chars read for each field.
  • You can use the modifier %*c to skip a char (the ;).

This should be fine:

int min = 0, sec = 0, sec_cent = 0;
char name[128], surname[128];

while ( fscanf(fp, "%127[^;]%*c%127[^;]%*c%2d'%2d''%2d", surname, name,
                                                         &min, &sec, &sec_cent) == 5 ) {
    // do something...
}
Community
  • 1
  • 1
Bob__
  • 12,361
  • 3
  • 28
  • 42