C++实现eval

本文介绍了一种不常见的C++实现eval的方法,通过在Windows环境下使用mingw-w64安装GCC并配置环境变量,将计算表达式写入cpp文件编译执行,结果输出到文本,然后读取。注意此方法娱乐性质,存在安全隐患,如非法字符串可能导致编译错误或执行危险命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++实现eval


实现一个函数double eval(string s),输入合法的表达式字符串,返回计算结果。

通常的实现方法是表达式树等等,下面看一种不一样的:

// eval.cpp
#include <iostream>
#include <fstream>
using namespace std;

double eval(string s)
{
    fstream fs("eval_calc.cpp", ios::out | ios::trunc);
    fs << "#include <iostream>" << endl;
    fs << "#include <fstream>" << endl;
    fs << "#include <cmath>" << endl;
    fs << "using namespace std;" << endl;
    fs << "int main()" << endl;
    fs << "{" << endl;
    fs << "    ofstream outfile;" << endl;
    fs << "    outfile.open(\"eval_answer.dat\", ios::out | ios::trunc);" << endl;
    fs << "    outfile << " << s << " << endl;" << endl;
    fs << "    outfile.close();" << endl;
    fs << "    return 0;" << endl;
    fs << "}" << endl;
    fs.close();

    system("g++ eval_calc.cpp -o eval_calc.exe");
    system(".\\eval_calc.exe");

    ifstream infile;
    infile.open("eval_answer.dat");
    double data;
    infile >> data;
    infile.close();
    system("del eval_calc.cpp");
    system("del eval_calc.exe");
    system("del eval_answer.dat");
    return data;
}

int main()
{
    string e;
    cout << "input an experssion: ";
    cin >> e;
    cout << eval(e) << endl;
    // system("pause");
    return 0;
}

windows下安装gcc(mingw-w64)并配置环境变量,编译运行:

PS C:\> g++ eval.cpp -o eval.exe
PS C:\> .\eval.exe
input an experssion: 1+2*(3-sqrt(4))
3

答案无误!皮这一下很开心!🤪


----------------8<-------------[ cut here ]----------------8<-------------


实现原理:新建下面的cpp文件,把要计算的表达式写入,编译执行,就会输出答案到文本中,再读取文本。

// eval_calc.cpp
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
    ofstream outfile;
    outfile.open("eval_answer.dat", ios::out | ios::trunc);
    outfile << experssion << endl;
    outfile.close();
    return 0;
}
experssion
answer
eval.exe
eval_calc.cpp
eval_calc.exe
eval_answer.dat



PS:仅供娱乐,存在漏洞,输入非法字符串会导致编译错误,甚至可能执行危险的命令。


----------------8<-------------[ end ]----------------8<-------------

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值