Parse GPS String for Time and Coordinates

Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void parse_gprmc(char *nmea) {
    // Your logic here
    int i =0;
    int j=0;
    int k=0;
    int m=0;
    int count = 0;
    char *buffer = (char *)malloc(sizeof(char)*(strlen(nmea)+1));
    char t[10] = {'\0'};
    char latitude[12] = {'\0'};
    char longitude[12] = {'\0'};
    //$GPRMC,123519,A,4807.038,N,01131.000,E
    while(nmea[i] != '\0')
    {
        while(nmea[i] != ',' && nmea[i] != '\0')
        {
            
            buffer[j++] = nmea[i++];
        }
        count++;
        i=i+1;
        
    }
    buffer[j] = '\0';

    //printf("%s\n", buffer);
    strncpy(t, &buffer[6], 2);
    t[2] = ':';
    strncpy(&t[3], &buffer[8], 2);
    t[5] = ':';
    strncpy(&t[6], &buffer[10], 2); 
    t[8] = '\0';
    strncpy(latitude, &buffer[13], 8);
    latitude[8] = ' ';
    strncpy(&latitude[9], &buffer[21], 1);
    strncpy(longitude, &buffer[22], 9);
    longitude[9] = ' ';
    strncpy(&longitude[10], &buffer[31], 1);
    
    printf("Time: %s\n", t);
    printf("Latitude: %s\n", latitude);
    printf("Longitude: %s\n", longitude);
}

int main() {
    char nmea[100];
    fgets(nmea, sizeof(nmea), stdin);
    parse_gprmc(nmea);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

$GPRMC,123519,A,4807.038,N,01131.000,E

Expected Output

Time: 12:35:19 Latitude: 4807.038 N Longitude: 01131.000 E