C++:将字符串转换为向量

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";