Split string with two comma separated numbers.

I have a two strings holding two integer Cartesian coordinate points, which could potentially be negative. What is the simplest way to extract them into four integer variables x2, x1, y2, and y1? Putting them into a vector would also be acceptable.

I was using stoi, but the code below breaks with negative numbers.

1
2
3
4
5
6
7
  double get_distance(string point1, string point2) {
    int x1 = stoi(point1); 
    int y1 = stoi(point1.erase(0,2));
    int x2 = stoi(point2);
    int y2 = stoi(point2.erase(0,2));
    return sqrt( pow( (x2 - x1) , 2) + pow( (y2 - y1) , 2) );
}
I don't know if this is the most "elegant" solution, but I did get the following working:

1
2
3
4
5
6
7
8
9
double get_distance(string point1, string point2) {
    char comma;
    int x1, y1, x2, y2 = 0;
    stringstream p1(point1);
    stringstream p2(point2);
    p1 >> x1 >> comma >> y1;
    p2 >> x2 >> comma >> y2;
    return sqrt( pow( (x2 - x1) , 2) + pow( (y2 - y1) , 2) );
}
Last edited on
Topic archived. No new replies allowed.