readfile - Trying to read formatted file in C -


i'm trying read formatted file in c sample line of file:

surname;name;minutes'seconds''one-hundredths of second

i wrote 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 name , surname strings, doesn't extract time minutes'seconds''one-hundredths of second , don't know why

can me?

there couple of things may want change in code:

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

this should 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 ) {     // something... } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -