解析c++中坐标字符串的最佳方法

Best way to parse coordinates string in C++

本文关键字:最佳 方法 字符串 坐标 c++ 解析      更新时间:2023-10-16

我想知道在c++中解析相同string中聚集在一起的坐标的最佳方法。

例子:

1,5
42.324234,-2.656264

结果应该是两个double变量…

如果字符串的格式总是像x,y,那么这应该足够了。

#include <string>
#include <sstream>
double x, y;
char sep;
string str = "42.324234,-2.656264";
istringstream iss(str);
iss >> x;
iss >> sep;
iss >> y;

使用while (std::getline(stream, line))提取每行,然后用line初始化std::istringstream。然后你可以像这样提取:

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