4

I've got some input like this: (50.1003781N, 14.3925125E) which is stored in const string & input. What I'm trying to do is to extract the brackets, get the number representing the GPS coordination - 50.1003781, save N and do the same for the second coord.

So here goes my code:

istringstream iStream(input);

char brackets[2]; //To store the brackets 
char types[2]; //To store if it is N/S or W/E
char delim; //To store ","
double degrees[2];

iStream >> brackets[0] >> degrees[0] >> types[0] >> delim;

//The delim loads the "," and here goes my problem with whitespace which is next

iStream >> degrees[1] >> types[1] >> brackets[1];

But it fails on loading degrees[1], it loads zero and tellg() says -1 probably because of whitespace after the comma. The parsed string should be like this:

cout << brackets[0]; // "("
cout << degrees[0]; // "50.1003781"
cout << types[0]; // "N"
cout << delim; // ","
cout << degrees[1]; // "14.3925125"
cout << types[1]; // "E"
cout << brackets[1]; // ")"

I've tried skipws and noskipws but with no effect. Can anybody help, please? Thanks a lot.

kubisma1
  • 307
  • 5
  • 13

1 Answers1

8

The problem is pretty subtle, but it has to do with the fact that the E in 14.3925125E is parsed in scientific notation. In math, the E suffix is an abbreviation for multiplying its operand by the exponentiation of 10 times the number that follows. For example, 5.23E4 in scientific notation means 5.23 * 10^4.

In your situation, since a number doesn't follow the E suffix, its parsed as an invalid floating point literal, so the number is not assigned to degrees[1].

Instead of reading the value into degrees[1] directly, I would recommend instead reading it into a string, parsing the floating-point part from the E, and convert and assign them to their respective variables.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Quick question, why does the following code not behave similar to the code in the question? [code](http://pastie.org/8971910) – viki.omega9 Mar 27 '14 at 01:42
  • @viki.omega9 You haven't described the difference in behavior between the two programs, but it's simply that you can only hold floating point values in scientific notation in objects of type `float` or `double`. You're extracting into an integer, so it only takes the integral part (`10`). And for the second part of the program you are extracting into the wrong variables, you should be doing `ss >> extra >> num >> deg`. [See here](http://ideone.com/nO4Nyt) – David G Mar 27 '14 at 11:14