我不会花时间重新发明轮子。我会为用户输入使用现有的脚本语言,我个人的选择是 lua,尽管许多其他语言都是可行的。
这大致就是您的应用程序使用 lua 作为解释器的样子。
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <string>
#include <iostream>
int main()
{
using namespace std;
string x,y;
cout << "Please enter x" <<endl;
cin >> x ;
cout << "please enter y" <<endl;
cin >> y;
//TODO: You may want to check that they've entered an expression
//
lua_State * L = lua_open();
// We only import the maths library, rather than all the available
// libraries, so the user can't do i/o etc.
luaopen_math(L);
luaopen_base(L);
// We next pull the math library into the global namespace, so that
// the user can use sin(x) rather than math.sin(x).
if( luaL_dostring(L,"for k,v in pairs(math) do _G[k] = v end") != 0)
{
std::cout<<"Error :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
// Convert x to an integer
x = "return "+x;
if( luaL_dostring(L,x.c_str()) != 0 )
{
std::cout<<"Error in x :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
int xv = lua_tointeger(L,-1);
lua_pop(L,1);
// Convert y to an integer
y = "return "+y;
if( luaL_dostring(L,y.c_str()) != 0 )
{
std::cout<<"Error in y :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
int yv = lua_tointeger(L,-1);
lua_pop(L,1);
int result = xv + yv ;
cout << result << endl;
return 0;
}
有了这个,您可以输入诸如1+sin(2.5)*3
.