我在字符串中有一个逻辑表达式,需要进行计算。在C++中有什么方法可以做到吗?
std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)";例:
if ((1 || 0) && (1 && 1) && (1 || 0 && 0))
{
std::cout << "true\n";
}发布于 2022-09-28 09:14:21
在C++中没有简单的内置方式来计算这样的逻辑表达式。如果要在运行时计算这样的表达式,则需要首先通过编写解析器将字符串解析为某种中间表示形式(例如表达式树),然后编写将该树夷为平地为单个值的计算器。
然后,假设
struct ExprTree { ... };
ExprTree parse(std::string const& input);
bool eval(ExprTree const& expr);这样的字符串表达式的结果可以使用
std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)";
if (eval(parse(exp)) {
// ...
}https://stackoverflow.com/questions/73876979
复制相似问题