2

I have an input file (ASCII) with arithmetics, e.g.
TEST;0.0;0.0+0.1;0.0+0.2

I can read the string and split it accordingly, so I already have elements of std::string. Now I wanted to use boost::lexical_cast<double> to store it in a double, comparable to an expression like:

double d = boost::lexical_cast<double>("0.0+0.1");

However, Boost throws

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what():  bad lexical cast: source type value could not be interpreted as target

Is there a good way to go, maybe without sscanf? (If sscanf would be capable of doing this at all...)

TIA

Gunnar
  • 213
  • 3
  • 13
  • 7
    wait, you expect lexical_cast to calculate 0.0+0.1 for you? – PlasmaHH Jul 17 '12 at 14:33
  • How complicated are you expressions? Arbitrary-depth nesting with parentheses? What operators do you want implemented? – robert Jul 17 '12 at 14:34
  • @PlasmaHH Yes, I thought so. Too much to ask? – Gunnar Jul 17 '12 at 14:43
  • You're going to need to parse out the result on your own. Perhaps using http://en.wikipedia.org/wiki/Reverse_Polish_notation and a custom parser. – Chad Jul 17 '12 at 14:44
  • @robert: Just division and addition, coordinates like 50 + 10./60. + 20./3600. – Gunnar Jul 17 '12 at 14:45
  • I'm suggesting that he parses his infix notation into RPN, then does the calculations on his own. – Chad Jul 17 '12 at 14:46
  • 1
    `lexical_cast` converts _values_ from one type to another, via a string representation, it's not an arithmetic expression parser, so yes, way too much to ask. (All it does is write the source value to a `stringstream` then read it out again as the target type, and iostreams can't interpret arithmetic expressions.) – Jonathan Wakely Jul 17 '12 at 14:52

2 Answers2

3

boost::lexical_cast is not a parser/calculator. You could use Boost.Spirit to do this. There's an O'Reilley example on how to implement such a calculator, but as you can see it's not straight-forward.

Questions OpenSouce C/C++ Math expression parser Library and Evaluating arithmetic expressions in C++ might be good starting points if you want to implement a simple parser.

Community
  • 1
  • 1
larsmoa
  • 12,604
  • 8
  • 62
  • 85
  • Thank you. Seems I was a little to demanding and naive. However, to much effort for little benefit... I changed the ASCII values by hand. Thanks nevertheless! – Gunnar Jul 20 '12 at 14:09
1

A solution could be splitting the strings again, if there's an arithmetic operator in the string, do the cast for both substrings and then do the arithemtic operation.

I don't think boost::lexical_cast or anything similar does this or is intended to do this.

Simon
  • 1,616
  • 2
  • 17
  • 39