0
是否可以将用户输入作为要在表达式中使用的变量?将用户输入作为运算符转换为表达式
scanf("%s", op); //User enters "==" or "!="
if(x op y)
//Go.
是否可以将用户输入作为要在表达式中使用的变量?将用户输入作为运算符转换为表达式
scanf("%s", op); //User enters "==" or "!="
if(x op y)
//Go.
号,你能做的最好的是一样的东西:
scanf("%s", &op);
if (strcmp(op, "==") == 0) {
result = x == y;
}
else if (strcmp(op, "!=") == 0) {
result = x != y;
}
// now use result
什么你实际上要求的是做EVAL的能力。一些动态语言(python等)支持它,但不支持C.即使支持eval,仍然需要为安全原因进行输入验证。
下面的C代码这是否符合一个抽象和调度表:
#include <stdio.h>
typedef int (*func)(int op1, int op2);
struct op {
char *opstr;
func op_func;
};
int add_func(int op1, int op2)
{
return op1 + op2;
}
int sub_func(int op1, int op2)
{
return op1 - op2;
}
struct op ops[] = { {"+", add_func}, {"-", sub_func} };
int main (int argc, char const* argv[])
{
int x = 10, y = 5, i = 0;
char op[10];
scanf("%s", &op);
for(i = 0; i < sizeof(ops)/sizeof(ops[0]); i++){
if(strcmp(ops[i].opstr, op) == 0){
printf("%d\n", ops[i].op_func(x, y));
break;
}
}
}
我编辑的反映一个事实,即C不设有运营商的关键字。 – dmckee 2011-03-24 02:04:51