简体   繁体   English

C++ 将字符串逻辑表达式转换为条件表达式

[英]C++ Convert string logical expression to conditional expression

I have a logical expression in string and need to evaluate.我在字符串中有一个逻辑表达式,需要求值。 Is there a way in C++ do it? C++有办法吗?

std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)";

Eg:例如:

if ((1 || 0) && (1 && 1) && (1 || 0 && 0))
    {
        std::cout << "true\n";
    }

There's no easy built-in way in C++ to evaluate logic expressions like that. C++ 中没有简单的内置方法来评估这样的逻辑表达式。 If you want to evaluate such an expression in runtime, you need to parse a string into some intermediate representation first (eg an expression tree) by writing a parser and write an evaluator that will flatten that tree into a single value.如果你想在运行时评估这样的表达式,你需要首先通过编写解析器将字符串解析为某种中间表示(例如表达式树),然后编写一个评估器,将该树展平为单个值。

Then, assuming然后,假设

struct ExprTree { ... };
ExprTree parse(std::string const& input);
bool eval(ExprTree const& expr);

you can get the result of such a string expression with你可以得到这样一个字符串表达式的结果

std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)";
if (eval(parse(exp)) {
    // ... 
}

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

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