102. Parse GPS String for Time and Coordinates

Back To All Submissions
Previous Submission
Next Submission

Code

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

void parse_gprmc(char *nmea) {
    // Your logic here
    int i = 0;
    int field_index = 0;
    int char_index = 0;
    char time[20] = {0}, lattitude[20] = {0}, longtitude[20] = {0}, lat_direction = ' ', long_direction = ' ';
    while (*(nmea + i) != '\0') {
        if (*(nmea + i) == ',') {
            field_index ++;
            char_index = 0;
        }
        else {
            if (field_index == 1) {
                time[char_index++] = *(nmea + i);
            }
            else if (field_index == 3) {
                lattitude[char_index++] = *(nmea + i);
            }
            else if (field_index == 4) {
                lat_direction = *(nmea + i);
            }
            else if (field_index == 5) {
                longtitude[char_index++] = *(nmea + i);
            }
            else if (field_index == 6) {
                long_direction = *(nmea + i);
            }
        }
        i ++;
    }
    if (time[0] != '\0') {
        printf("Time: %c%c:%c%c:%c%c\n", time[0],time[1],time[2],time[3],time[4],time[5]);
    }
    if (lattitude[0] != '\0') {
        printf("Latitude: %s %c\n", lattitude, lat_direction);
    }
    if (longtitude[0] != '\0') {
        printf("Longitude: %s %c\n", longtitude, long_direction);
    }
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote