c - Can I get some advice on the easiest way to parse the provided string -
the string: phillip:22021999;football,tennis,basketball
i want line read these variables in following manner:
char name[50] = phillip int dob = 22021999 char (*a[10])[14] = 'football', 'tennis','basketball'
any advice appreciated.
#include <stdio.h> #include <stdlib.h> #include <string.h> enum { max_num_of_field = 10, field_size = 14 }; int main(void) { char *the_string = "phillip:22021999;football,tennis,basketball\n"; char name[50]; int dob; char (*a[max_num_of_field])[field_size] = { null }; char rest[max_num_of_field*(field_size+1)]; sscanf(the_string, "%49[^:]:%d;%149[^\n]", name, &dob, rest); int i;//, num_fields = 0; char *p; for(i = 0, p = strtok(rest, ",\n"); < max_num_of_field && p ; ++i, p = strtok(null, ",\n")){ char (*afield)[field_size] = calloc(1, sizeof(char[field_size])); strncpy(*afield, p, field_size-1); a[i] = afield; } printf("name:%s\n", name); printf("dob:%08d\n", dob); printf("notes:\n"); for(i = 0; < max_num_of_field; ++i){ if(a[i]){ printf("%s\n", a[i]); //free(a[i]); } else { break; } } return 0; }
Comments
Post a Comment