嘿,我想知道如何把一个字符'+‘变成一个运算符。例如,如果我有
char op = '+'
cout << 6 op 1;谢谢。
发布于 2012-10-30 23:29:11
切换方法是使用SImple语句
switch (op)
{
case '+':
res = x + y;
break;
case '-':
res = x - y;
break;
case '*':
res = x * y;
break;
}发布于 2012-10-30 23:29:32
我不认为有一种像你写的那样的方法,但你可以做一些类似于
int do_op(char op, int a, int b)
{
switch(op)
{
case '+':
return a+b;
break;
case '-':
return a-b;
break;
case '*':
return a*b;
break;
case '/':
return a/b;
break;
default:
throw std::runtime_error("unknown op")
}
}发布于 2012-10-31 00:35:32
你可以使用老办法#define:
#define op +
std::cout << 6 op 1;然而,它的用途是有限的。
如果您想在纯C++中执行此操作,则必须显式地或在外部库(如tetzfamily.com y.com/temp/EvalDoc.htm或codeproject.com/Articles/7939/C-based-Expression-Evaluation-Library)). )中使用切换语法
另一种方法是使用外部程序,如bc:
char op = '+';
std::string s;
s += "6";
s += op;
s += "4";
system(("echo " + s + "|bc").c_str());如果您想在以后使用结果,请检查popen函数或C++ equivalent。
https://stackoverflow.com/questions/13142270
复制相似问题