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;
}
PS:仅供娱乐,存在漏洞,输入非法字符串会导致编译错误,甚至可能执行危险的命令。
----------------8<-------------[ end ]----------------8<-------------