简体   繁体   中英

Using boost::lexical_cast with arithmetic expressions

I have an input file (ASCII) with arithmetics, eg
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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM