从特定字符串中取出双精度

taking doubles out of a specific string

本文关键字:双精度 字符串      更新时间:2023-10-16

我所有的字符串都将被格式化,例如

std::string templine;
templine = "vertex 4.5 2.2 1";

当然,将输入不同的双精度,但顶点将始终存在我试过stod但我不知道该怎么办。

只是为了测试它,我这样做了:

    std::string orbits = "Vertex 4.5 2.3 5";
double x,y,z;
std::size_t offset = 0;
z = std::stod(&orbits[7], &offset);
y = std::stod(&orbits[offset+2]);
x = std::stod(&orbits[offset+2]);
std::cout << "z " << z << std::endl;
std::cout << "y " << y << std::endl;
std::cout << "x " << x << std::endl;

它给了我这个错误

在抛出"std::invalid_argument"实例后终止调用 什么(): 斯托德中止

处理此问题的一种简单方法是将字符串加载到std::stringstream中,然后使用其operator >>提取不同的部分。 在示例中,我使用一个名为 eater 的虚拟字符串,用于从字符串中提取"Vertex"部分。

std::stringstream ss(orbits)
std::string eater;
ss >> eater; //consumes "Vertex"
ss >> x >> y >> z; // gets the doubles

我们甚至可以确定提取部分的范围,以便临时stringstringstream仅用于提取,例如

{
    std::stringstream ss(orbits)
    std::string eater;
    ss >> eater; //consumes "Vertex"
    ss >> x >> y >> z; // gets the doubles
}
// now ss and eater are gone and x, y and z are populated.

如果您不喜欢这样的自由范围,也可以将其作为一个函数来执行。