arrays - Parsing substrings from a string with "sscanf" function in C -
i have gps string below:
char gps_string[] = "$gprmc,080117.000,a,4055.1708,n,02918.9336,e,0.00,316.26,00,,,a*78";
i want parse substrings between commas below sequence:
$gprmc 080117.000 4055.1708 . . .
i have tried sscanf function below:
sscanf(gps_string,"%s,%s,%s,%s,%s,",char1,char2,char3,char4,char5);
but not working. char1 array gets whole string if use above function.
actually have used strchr function in previous algorithm , got work it's easier , simplier if can work sscanf , parameters in substring.
by way, substrings between commas can vary. comma sequence fixed. example below gps string example not contain of parts because of sattellite problem:
char gps_string[] = "$gprmc,001041.799,v,,,,,0.00,0.00,060180,,,n*"
there have been number of comments in other answers stating there number of problems strtok()
, suggesting using strpbrk()
instead. example of how used can found @ arrays , strpbrk in c
i not have compiler available not test this. have typos or other misteaks in code, sure can figure out meant.
in case use
char *string_buffer = gps_string; char *start = string_buffer; char *end; char *fields[maxfields]; int = 0; int n = 0; char *match = null; while (end = strpbrk(start, ",")) // pointer next delimiter { /* found it, allocate enough space , nul */ /* if there ar 2 consecutive delimiters, nul gets entered */ n = end - start; match = malloc(n + 1); /* copy , nul terminate */ /* note if n 0, nothing copied not need test */ memcpy(match, start, n); match[n] = '\0'; printf("found field entry: %s\n", match); /* save actual match string pointer fields array*/ /* since match pointer in fields, not need freed */ fields[i++] = match; start = end + 1; } /* check last element in gps_string not , final field, has nul termination of string */ n = strlen(start); match = malloc(n + 1); /* note if n 0, terminator put in */ strcpy(match, start); printf("found field entry: %s\n", match); fields[i++] = match; printf("total number of fields: %d\n", i);
Comments
Post a Comment