Just define a variable of type Identity, and then use strncpy() to copy each token into the relevant field of the struct:
#include <stdio.h>
#include <string.h>
#define STRNCPY_STRUCT_EL(string_field, src) strncpy(string_field, src, sizeof(string_field) - 1 )
char strExample[]="Andrew;Smith;18;Wall Street;New York;10011;USA";
typedef struct Identity{
char firstName[20];
char lastName[20];
char age[5];
char street[64];
char city[20];
char postCode[8];
char country[20];
}Identity;
void textParse(Identity *id)
{
char *ptr = strExample;
char *token;
int i = 0;
memset(id, 0, sizeof(*id));
while ((token = strsep(&ptr,";")) != NULL)
//while ((token = strtok(ptr,";")) != NULL) //I used this in my test
{
// ptr = NULL; //I used this in my test, to fit strtok
switch(i++)
{
case 0:
STRNCPY_STRUCT_EL(id->firstName, token);
break;
case 1:
STRNCPY_STRUCT_EL(id->lastName, token);
break;
case 2:
STRNCPY_STRUCT_EL(id->age, token);
break;
case 3:
STRNCPY_STRUCT_EL(id->street, token);
break;
case 4:
STRNCPY_STRUCT_EL(id->city, token);
break;
case 5:
STRNCPY_STRUCT_EL(id->postCode, token);
break;
case 6:
STRNCPY_STRUCT_EL(id->country, token);
break;
}
}
}
int main(int argc, char **argv) {
Identity id;
textParse(&id);
printf("Identity:\n%s %s, %s y.o.\nLives in %s, %s (%s - %s)\n",
id.firstName, id.lastName, id.age, id.street, id.city, id.postCode, id.country);
return 0;
}
- Basically I checked the position of the token and then I copied it in the corresponding position of the struct. I used a
switch-case. Not so elegant but it works
- I copied it using a macro that automatically calculates the size of the field. I want to copy
size-1 characters as I want to leave room for the string terminator '\0'
- It works because I previously
memseted the whole struct to 0, so that after strncpy the string terminator is for sure where it must be
- I had to change
textParse() signature in order to accept a pointer to Identity. Inside it I skipped sanity checks (for example checks against NULL pointers). I recommend adding them into your final implementation
- This implementation truncates any token longer than the corresponding
Identity field
Output:
Identity:
Andrew Smith, 18 y.o.
Lives in Wall Street, New York (10011 - USA)