#include <stdio.h> #include <string.h> typedef struct{ char time[10]; char latitude[20]; char NS; char longitude[20]; char EW; }GPS_t; void parse_gpms(char *input, GPS_t* gps){ char token[7][50] = {0}; int count_row = 0, count_col = 0; // token: // [0]=$GPMS [1]=time [2]=status [3]=latitude [4]=NS [5]=longitude [6]=EW for(int i = 0; input[i] != '\0'&&count_row < 7; i++){ if(input[i] == ','){ token[count_row][count_col] = '\0'; count_row++; count_col = 0; continue; } if(count_col < 49){ token[count_row][count_col] = input[i]; } count_col++; token[count_row][count_col] = '\0'; } if(strlen(token[1]) >= 6){ snprintf(gps->time, sizeof(gps->time), "%.2s:%.2s:%.2s", token[1], token[1] + 2, token[1] + 4); } strcpy(gps->latitude, token[3]); strcpy(gps->longitude, token[5]); gps->NS = token[4][0]; gps->EW = token[6][0]; } void printf_gpms(GPS_t *gps){ printf("Time: %s\n",gps->time); printf("Latitude: %s %c\n", gps->latitude, gps->NS); printf("Longitude: %s %c\n", gps->longitude, gps->EW); } int main(){ char input[100]; fgets(input, sizeof(input), stdin); input[strcspn(input, "\n")] = '\0'; GPS_t gps; parse_gpms(input, &gps); printf_gpms(&gps); }
Test Cases
Test Results
Input
$GPRMC,123519,A,4807.038,N,01131.000,E
Expected Output
Time: 12:35:19 Latitude: 4807.038 N Longitude: 01131.000 E