Parse GPS String for Time and Coordinates

Code

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

void parse_gprmc(char *nmea) {
    // Your logic here
    char time[7] = {0};
    char lat[15] = {0};
    char lon[15] = {0};
    char ns = 0, ew = 0;

    int field = 0;
    int j = 0;

    while (*nmea)
    {
        if (*nmea == ',')
        {
            field++;
            j = 0;
            nmea++;
            continue;
        }

        switch (field)
        {
        case 1:     // Time
            time[j++] = *nmea;
            break;

        case 3:     // Latitude
            lat[j++] = *nmea;
            break;

        case 4:     // N/S
            ns = *nmea;
            break;

        case 5:     // Longitude
            lon[j++] = *nmea;
            break;

        case 6:     // E/W
            ew = *nmea;
            break;
        }

        nmea++;
    }

    printf("Time: %c%c:%c%c:%c%c\n",
           time[0], time[1], time[2], time[3], time[4], time[5]);

    printf("Latitude: %s %c\n", lat, ns);
    printf("Longitude: %s %c\n", lon, ew);
}

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