All submissions

Parse GPS String for Time and Coordinates

Code

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

// helper function to convert hhmmss to hh:mm:ss
void format_time(const char* raw, char* out, size_t out_size)
{
    // Fallback to zeros for invalid input
    if(!raw || strlen(raw) < 6 || out_size < 9)
    {
        snprintf(out, out_size, "00:00:00");
    }
    
    snprintf(out, out_size, "%c%c:%c%c:%c%c",
    raw[0], raw[1], raw[2], raw[3], raw[4], raw[5]);
}

void parse_gprmc(char *nmea) {
    // Your logic here
    // edge case
    if(!nmea) return;
    // Copy the data to a buffer
    char buf[128];
    strncpy(buf, nmea, sizeof(buf) - 1);
    buf[sizeof(buf) - 1] = '\0'; // add delimiter
    // tokenize the buffer
    char* fields[7] = {0}; // read and parse only the first 7
    int i = 0;
    char* token = strtok(buf, ",");
    while(token && i < 7)
    {
        fields[i++] = token;
        token = strtok(NULL, ",");
    }

    if(i < 7) return; // Not enough fields

    // Format time
    char UTC_Time[9];
    format_time(fields[1], UTC_Time, sizeof(UTC_Time));

    printf("Time: %s\n", UTC_Time);
    printf("Latitude: %s %s\n", fields[3], fields[4]);
    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

 

 

 

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