Ian Blair
Ian Blair

Reputation: 13

Parsing C string

I'm quite unfamiliar with C. A comma sepearted string comes in and I need to untangle it. Some bits correspond to numerical values, others to words etc.

Input

char str_in;

str_in = "$GPRMC,114353.000,A,6016.3245,N,02458.3270,E,0.01,0,A*69";

Output

#include <string.h>
float lat, lon, time;

time = 114353.000;
lat = 60+(1/60)*16.3245; //Conversion to decimal degrees
lon = 024+(1/60)*58.3270;

All the spacings remain unchanged. The section I have struggled with is extracting the first two/three digits from the latitude/longitude and treating them differently. Can anyone help?

Upvotes: 0

Views: 1786

Answers (3)

Ian Blair
Ian Blair

Reputation: 13

http://nmea.sourceforge.net/#features

Looks good.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490108

I'd probably do something like this:

sscanf(str_in, %[^,],%f,%c,%f,%c,%f",
    command,
    &packed_time,
    &fix_status,
    &packed_lat,
    &NS,
    &packed_long);

struct lat_long { 
    int degrees;
    double minutes;
};

lat_long lat, long;
lat.degrees = packed_lat / 100;
lat.minutes = packed_lat - lat.degrees;

long.degrees = packed_long / 100;
long.minutes = packed_long - long.degrees;

Upvotes: 0

Larry Watanabe
Larry Watanabe

Reputation: 10184

Uses strtok. Here's a reference:

http://www.metalshell.com/source_code/31/String_Tokenizer.html

/* strtok example by [email protected]
 *
 * This is an example on string tokenizing
 *
 * 02/19/2002
 *
 * http://www.metalshell.com
 *
 */

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

int main(int argc, char *argv[])
{
        int x = 1;
        char str[]="this:is:a:test:of:string:tokenizing";
        char *str1;

        /* print what we have so far */
        printf("String: %s\n", str);

        /* extract first string from string sequence */
        str1 = strtok(str, ":");

        /* print first string after tokenized */
        printf("%i: %s\n", x, str1);

        /* loop until finishied */
        while (1)
        {
                /* extract string from string sequence */
                str1 = strtok(NULL, ":");

                /* check if there is nothing else to extract */
                if (str1 == NULL)
                {
                        printf("Tokenizing complete\n");
                        exit(0);
                }
                /* print string after tokenized */
                printf("%i: %s\n", x, str1);
                x++;
        }
        return 0;
}

Upvotes: 2

Related Questions