C++: Convert string to a vector

2019-06-05 02:39发布

问题:

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:

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:

vector<double> Param and give me the following output:

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

回答1:

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

Live Example

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

To

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