1

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.

2
  • stod Commented Mar 19, 2013 at 11:49
  • You first have to decide whether you're writing C or C++, because the answer is different for the two languages. Commented Mar 19, 2013 at 12:06

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Note, however, that although std::regex with GCC 4.7 compiles just fine, it is actually very dysfunctional.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.