I have a string with lots of different characters similar to: "$: " "213.23453" How do i extract the double value 213.23453 and store it in a variable, it's C++/C and i cant use lambdas.
3 Answers
You can use "poor man's regex" of the sscanf function to skip over the characters prior to the first digit, and then reading the double, like this:
char *str = "\"$: \" \"213.23453\""; double d; sscanf(str, "%*[^0-9]%lf", &d); Note the asterisk after the first percentage format: it instructs sscanf to read the string without writing its content into an output buffer.
Here is a demo on ideone.
Comments
Use a regular expression.
[$]?[0-9]*(\.)?[0-9]?[0-9]?
This should match those with a $ sign and those without.
Boost.Regex is a very good regular expression library
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
If you're using a C++11 compliant compiler, use std::regex unless you have good reason to use something else.
1 Comment
std::regex with GCC 4.7 compiles just fine, it is actually very dysfunctional.Pure C++ solution could be to manually cut off the trash characters preceding the number (first digit identified by std::isdigit) and then just construct a temporary istringstream object to retrieve the double from:
std::string myStr("$:. :$$#&*$ :213.23453$:#$;"); // find the first digit: int startPos = 0; for (; startPos < myStr.size(); ++startPos) if (std::isdigit(myStr[startPos])) break; // cut off the trash: myStr = myStr.substr(startPos, myStr.size() - startPos); // retrieve the value: double d; std::istringstream(myStr) >> d; but C-style sscanf with appropriate format specified would suffice here as well :)
stod