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).
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
Use istream_iterator
s.
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{}};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With