apascual
apascual

Reputation: 2980

Best way to parse coordinates string in C++

I am wondering which would be the best way to parse coordinates that come together in the same string in C++.

Examples:

1,5
42.324234,-2.656264

The result should be two double variables...

Upvotes: 1

Views: 2756

Answers (2)

stardust
stardust

Reputation: 5998

If the format of the string is always like x,y, then this should be enough.

#include <string>
#include <sstream>

double x, y;
char sep;
string str = "42.324234,-2.656264";
istringstream iss(str);

iss >> x;
iss >> sep;
iss >> y;

Upvotes: 5

Joseph Mansfield
Joseph Mansfield

Reputation: 110728

Extract each line using while (std::getline(stream, line)) and then initialise a std::istringstream with line. Then you can extract from it like so:

double x, y;
if (line_stream >> x &&
    line_stream.get() == ',' &&
    line_stream >> y) {
  // Extracted successfully
}

Upvotes: 1

Related Questions