Separating String Into three Separate Doubles

Viewed 88

I have a string of a line I read from a file. String:("2021.2 12341.29 42.1"). I need to extract each of the three numbers into a double for each value which is shown by each space to insinuate a new number is there. The numbers will not always have the same spacing because I am doing this for multiple lines so I cant just go by the same exact point in the spacing. Here's what I have so far.

string vert; //I already got the read line so here for example I am subing in a value for vert.
vert = "2021.2 12341.29 42.1";
double num1, num2, num3;

for (int i = 0; i < vert.length(); i++){

...
}
2 Answers

Use std::istringstream:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
   std::string vert = "2021.2 12341.29 42.1";
   double num1, num2, num3;
   std::istringstream strm(vert);
   strm >> num1 >> num2 >> num3;
}

The solution std::stringstream presented by @PaulMcKenzie's answer is what you need.

I'll add that it works very well if you already know how many doubles are in the string, but if you don't, you can't really use it like that, you would need a variable size container that can accomodate your variables, like std::vector.

Online demo

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::string vert;
    vert = "2021.2 12341.29 42.1";

    std::vector<double> nums;   //vector of doubles
    double temp;                //temporary to hold the converted double
    
    std::stringstream ss(vert); //convert to stream
    while(ss >> temp){
        nums.push_back(temp);   //add numbers to the vector
    }
}
Related