从特定字符串中取出双精度
taking doubles out of a specific string
我所有的字符串都将被格式化,例如
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
我们甚至可以确定提取部分的范围,以便临时string
和stringstream
仅用于提取,例如
{
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.
如果您不喜欢这样的自由范围,也可以将其作为一个函数来执行。
相关文章:
- 如何在C++中的同一函数中使用字符串和双精度
- C 字符串返回字符串的整数/双精度/长整型值
- 如何从字符串转换为双精度*
- C++如何将字符串逐行转换为双精度
- 如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将双精度值转换为 char 变量时字符串流如何工作
- 在 c++ 中从双精度转换为字符串
- 从字符串转换为双精度和整数 - C++
- 如何从char16_t字符串文字中读取双精度?
- 分析字符串中的双精度和单词
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++将包含非人类可读数据的字符串转换为 200 双精度
- 将大双精度转换为科学记数法以用作字符串?
- 字符串和双精度的麻烦,等值后再得到一个数字
- 如何从字符串流中提取双精度
- 如何调用返回双精度或字符串并将其保存在地图上但作为对象的类的方法
- 在C++中使用atof将带小数的字符串转换为双精度字符串