在 C++ 中,可以使用动态编译器来实现类似于 Python 中 eval 函数的功能。下面是一个简单的示例:

#include <iostream>
#include <string>
#include <cstdlib>

class Eval {
public:
    static int eval(const std::string& expression) {
        std::string command = "echo '\";
        command += expression;
        command += "\' | bc";
        FILE* pipe = popen(command.c_str(), "r");
        if (!pipe) {
            std::cerr << "Error: Failed to execute command." << std::endl;
            return 0;
        }
        char buffer[128];
        std::string result = "";
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL) {
                result += buffer;
            }
        }
        pclose(pipe);
        return std::stoi(result);
    }
};

int main() {
    std::string expression = "2 + 3 * 4";
    int result = Eval::eval(expression);
    std::cout << "Result: " << result << std::endl;
    return 0;
}

上述代码通过调用外部命令bc,实现了对数学表达式的求值。在这个示例中,表达式为2 + 3 * 4,结果为14。你可以根据需要修改表达式,或者添加更多的数学函数和运算符来满足你的需求。请注意,这种方法不适用于执行任意的代码,仅适用于数学表达式的求值。


原文地址: https://www.cveoy.top/t/topic/pT6N 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录