简体   繁体   中英

What is the proper way to use struct in C?

I know struct in C is a collection of data, but I'm not sure if I can manipulate it in the following way:-

Say hypothetically I have something like the following:

typedef struct { 
    char id[IDSIZE];
    name name;
    int score;
} record;

If I wanted to record data, can I simply have a line like:

sscanf(line, "%s %s %d", &record);

to store the line to the record itself?

record is your type name. Like int or char . So you have to declare a variable of type record .

record currentRecord;

sscanf needs one variable address for every format token

sscanf(line, "%s %s %d", &currentRecord); //Fail
sscanf(line, "%s %s %d", &currentRecord.id, &currentRecord.name, &currentRecord.score); //This will work only if name is type of char*

name name won't work. Variable and type name must be different.

The answer by JD already points out the problems and how to fix them. I wont to repeat them here to address just that.

My suggestion is to create couple of functions:

int sscanf_record(char str[], record *rec)
{
   int n = sscanf(str, "%s %s %d", rec->id, rec->name, &(rec->id));
   if ( n == EOF )
   {
      return n;
   }
   return ( n == 3 ? 1 : 0);
}

int fscanf_record(FILE* fptr, record *rec)
{
   int n = fscanf(fptr, "%s %s %d", rec->id, rec->name, &(rec->id));
   if ( n == EOF )
   {
      return n;
   }
   return ( n == 3 ? 1 : 0);
}

Then, in rest of our code, you can these functions instead of having to repeat the details.

record myrecord;
if ( sscanf_record(line, &myrecord) != 1 )
{
   // Problem. Deal with it.
}
else
{
   // Use the data
}

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