C++:将字符串转换为向量<double> [英] C++: Convert string to a vector&lt;double&gt;

查看:64
本文介绍了C++:将字符串转换为向量<double>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 比较陌生,想将数字的字符字符串转换为双精度向量.这些字符串将具有不同的长度,但它们的长度将始终是已知的.例如:

I am relatively new to C++ and would like to convert char strings of numbers to a vector of doubles. These strings will have different length, but their lengths will always be known. For example:

我有一个名为myValue"的 char* 字符串,它看起来像这样 "0.5 0.4 1 5" 并且具有已知长度,length=4.

I have a char* string called "myValue" which looks like this "0.5 0.4 1 5" and has a known length, length=4.

我想将此字符串转换为双精度向量,如下所示:

I would like to convert this string to a vector of doubles like this:

vectorParam 并给我以下输出:

Param[0]=0.5, Param[1]=0.4, Param[2]=1, Param[3]=5

推荐答案

您可以使用 std::stringstream.我们会将字符串存储到 stringstream 中,然后使用 while 循环从中提取 double 部分.

You can do this with a std::stringstream. We would store the string into the stringstream and then extract the double parts out of it with a while loop.

std::stringstream ss;
std::vector<double> data;
char numbers[] = "0.5 0.4 1 5";
ss << numbers;
double number;
while (ss >> number)
    data.push_back(number);

现场示例

由于我们使用标准容器,我建议使用 std::string 而不是 char [] 然后我们可以更改

Since we are using standard container I would suggest using a std::string instead of a char [] and then we could change

char numbers[] = "0.5 0.4 1 5";

std::string numbers = "0.5 0.4 1 5";

这篇关于C++:将字符串转换为向量<double>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆