Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple doubles that are in a string, separated by spaces, in C++?

Tags:

c++

string

double

I need to read in a string such as:

string str = "3 - 90.2 85.54 93.0";

...in this format. The first number shows the number of doubles, followed by a " = " and then that many doubles separated by spaces). I know how to read the first number as an int to find the number of doubles. However, what is troubling me is the reading of the doubles. I tried using the stod function.

string str = "90.2 85.54 93.0";
size_t sz;

double x = stod(str,&sz);
double y = stod(str.substr(sz));
double z = stod(str.substr(sz));

However, this can only read up to 2 doubles since str.substr(sz) will read to the end of the string, and the doubles can be with different decimals (it could be 89.54 or 89 or 89.6), so I can't use substr since that requires me to know how many characters to read from the starting index.

Is there any way to read in these unknown count of doubles with unknown number of decimal numerals? Is there another method such as substr to read up to a specific index or character? I just want them to be able to be read one by run. I can later store it into a double array (which I know how to do).

like image 860
user3397612 Avatar asked Nov 08 '14 04:11

user3397612


2 Answers

you can use stringstream

string str = "3 - 90.2 85.54 93.0";
stringstream ss(str);
int num;   ss >> num; //read 3
char c;    ss >> c;    // read "-"
double d1; ss >> d1;   // read 1
double d2; ss >> d2;   // read 2
double d2; ss >> d2;   // read 3
like image 61
Peter Li Avatar answered Nov 15 '22 14:11

Peter Li


Use istream_iterators.

std::vector<double> xyzzy{std::istream_iterator<double>{std::istringstream{str}}, std::istream_iterator{}};

Note that streams don't have move constructors in GCC so you'll need to declare your istringstream and pass a reference to it if you're using GCC, like this:

std::istringstream temp{str};
std::vector<double> xyzzy{std::istream_iterator<double>{temp}, std::istream_iterator{}};
like image 1
Jonathan Mee Avatar answered Nov 15 '22 15:11

Jonathan Mee