How to parse almost-defined string in C?

111 Views Asked by At

I have a string to parse. This string has an almost-defined format with GPS coordinates. I want to get the coordinates.

Sometimes I have this :

09:24:29 N 012:34:35 W, 09:22:18 N 012:33:55 W

But sometimes I have extra whitespaces :

09:24:29 N 012:34:35 W , 09:22:18 N 012:33:55 W

But sometimes I have no whitespaces :

09:24:29 N 012:34:35 W,09:22:18 N 012:33:55 W

But sometimes I have decimal :

09:24:29.3 N 012:34:35.2 W, 09:22:18.1 N 012:33:55.6 W

So my question is : What's the most reliable and portable way to read these GPS coordinates in C ?

I first started with sscanf, but I have a lot of issues with extra (or not) whitespaces and decimal .

2

There are 2 best solutions below

0
On BEST ANSWER

I suggest you first split into multiple strings on comma, then using sscanf will be simpler as you simply doesn't have to care about leading or trailing space.

As for the decimal point, if you read as float it will be able to read both "18" and "18.1". However, you might need to be aware of some of the problems with floating point data on binary computers.

1
On

Thanks Joachim, using floating is a good idea.

This should work :

sscanf( gps_string, "%d:%d:%f %c %d:%d:%f %c", ...);

sscanf( strchr(gps_string, ',')+1, "%d:%d:%f %c %d:%d:%f %c", ...);

Thanks for your help and idea !