1

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 .

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Vincent
  • 165
  • 10
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! Also see [how to ask](http://stackoverflow.com/questions/how-to-ask) – Eregrith Jun 09 '15 at 09:32
  • 1
    Start with defining the *grammar*. Then build a parser for it. You might be able to use a library for the second part. (In C++ I'd probably plump for Boost Spirit). – Bathsheba Jun 09 '15 at 09:34
  • processing strings is always messy in C. could you use a different language? If not, either go with a parser as @Bathsheba suggests, or if the grammar is easy enough, you can process the string char by char and build your values manually. – Andreas Grapentin Jun 09 '15 at 09:41
  • another approach might be to pre-process the string to get something easier to parse (e.g., stripping unnecessary whitespaces), and then defining a grammar for the "canonized" string. – akappa Jun 09 '15 at 09:48

2 Answers2

2

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.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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 !

Vincent
  • 165
  • 10
  • There isn't a need for two `sscanf`s. You can simply use `sscanf( gps_string, "%d:%d:%f %c %d:%d:%f %c , %d:%d:%f %c %d:%d:%f %c", ...);` – Spikatrix Jun 09 '15 at 10:06