Link to home
Start Free TrialLog in
Avatar of lzha022
lzha022

asked on

question about sscanf

Hello experts,
Currently i have a method with code like this:
  sscanf(s, "%lf %lf %lf %lf %d %d ", &x, &y, &z, &weight, &se, &sl);   --- m1
this will read in the info about some 3D pionts from a file 'output'.
Now i am going to add one more property of the 3D points called 'name' and 'name' will be written to the 'output' file, so i changed the code to this:
   char name[20];
   sscanf(s, "%lf %lf %lf %lf %d %d %s", &x, &y, &z, &weight, &se, &sl, &name);  -- m2
The problem happens because not all 'output' files have 'name' saved. I want to add some checking: if there is a 'name', use m2 otherwise use m1.
Could anyone give me some idea how to add such a checking? How do i check 'name' exists?
Thanks.
SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dr_country
dr_country

If your file is a text file where you have 'name' as a stand alone label, you can search for it. For example, you can search the file line by line and if you find 'name', use your sscanf function, but that is if 'name' is in the file in its own line:

#include <stdio.h>

int searchString(FILE *fd, char name[25])
{
     char buffer[20];
     
     /* search through the file line by line.... */
     while ( (fgets(buffer, 20, fd)) != NULL )
     {
          if( strcmp(buffer,"name\n") == 0 )
               return 1;
     }
     return 0;
}
     

main()
{
     FILE *fd;
     char name[] = "name\n";
     char filename[] = "searchFile.txt";
     if ( (fd = fopen(filename, "r")) == NULL )
     {
          printf("Error %s\n", filename);
          return 1;
     }

     if( searchString(fd, name) )
        sscanf(s, "%lf %lf %lf %lf %d %d ", &x, &y, &z, &weight, &se, &sl);   \*--- m1  */
     else
        sscanf(s, "%lf %lf %lf %lf %d %d %s", &x, &y, &z, &weight, &se, &sl, &name); \*--- m2  */
   
     /* depending on your compiler you might not need the system() function */
     /*system("pause"); */
     fclose(fd);
     return 0;
}


ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lzha022

ASKER

Thanks all for your reply.
I forgot to mention, 'name' variable is entered by user so i have no way to know what it is.
Kdo`d method sounds good, i will try this first.
Thanks again
Avatar of lzha022

ASKER

Hi Paul,
I just read your comments. If this can work, it would be the easist way. I will try it now.

Thanks
Avatar of lzha022

ASKER

Thanks everyone. Paul`s method is really easy. Kdo`s method will also work i think though i have not tried it yet.
Thanks again.
Alison