简体   繁体   English

在算法表达式中使用boost :: lexical_cast

[英]Using boost::lexical_cast with arithmetic expressions

I have an input file (ASCII) with arithmetics, eg 我有一个带算术的输入文件(ASCII),例如
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 . 我可以读取字符串并相应地对其进行拆分,因此我已经有了std::string元素。 Now I wanted to use boost::lexical_cast<double> to store it in a double, comparable to an expression like: 现在,我想使用boost::lexical_cast<double>将其存储在double中,类似于以下表达式:

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 ? 是否有个不错的路要走,也许没有sscanf (If sscanf would be capable of doing this at all...) (如果sscanf完全能够做到这一点...)

TIA TIA

boost::lexical_cast is not a parser/calculator. boost::lexical_cast不是解析器/计算器。 You could use Boost.Spirit to do this. 您可以使用Boost.Spirit来做到这一点。 There's an O'Reilley example on how to implement such a calculator, but as you can see it's not straight-forward. 关于如何实现这样一个计算器,有一个O'Reilley的示例 ,但是正如您所看到的那样,它不是直截了当的。

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. 问题如果您想实现一个简单的解析器, OpenSouce C / C ++数学表达式解析器库评估C ++中的算术表达式可能是一个很好的起点。

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. 我不认为boost :: lexical_cast或类似的东西会这样做或打算这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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