Parse GPS String for Time and Coordinates

Code

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

void parse_gprmc(char *nmea) {
    int hh, mm, ss;
    char lat[20], ns;
    char lon[20], ew;
    char status;

    // Use sscanf to parse the fields based on the comma delimiters
    // %2d%2d%2d: Breaks the first 6 digits into HH, MM, and SS
    // %c: Reads the single character status (A/V)
    // %[^,]: Reads everything until the next comma (used for coordinates)
    if (sscanf(nmea, "$GPRMC,%2d%2d%2d,%c,%[^,],%c,%[^,],%c", 
               &hh, &mm, &ss, &status, lat, &ns, lon, &ew) >= 7) {
        
        printf("Time: %02d:%02d:%02d\n", hh, mm, ss);
        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