Parse GPS String for Time and Coordinates

Code

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

void parse_gprmc(char *nmea) {
    // Your logic here
    char fields[7][20];
    int i = 0, j = 0, k = 0;

    // Extract first 7 fields
    while (nmea[i] != '\0' && k < 7) {
        if (nmea[i] == ',') {
            fields[k][j] = '\0';
            k++;
            j = 0;
        } else {
            if (j < 19) {
                fields[k][j++] = nmea[i];
            }
        }
        i++;
    }
    if (k < 7 && j > 0) {
        fields[k][j] = '\0';
        k++;
    }

    // fields:
    // 0 = $GPRMC
    // 1 = time
    // 2 = status
    // 3 = latitude
    // 4 = N/S
    // 5 = longitude
    // 6 = E/W

    // Format time HHMMSS → HH:MM:SS
    char *time = fields[1];

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

    // Longitude
    printf("Longitude: %s %s\n", fields[5], fields[6]);
}

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