2011-03-24 80 views

回答

6

号,你能做的最好的是一样的东西:

scanf("%s", &op); 
if (strcmp(op, "==") == 0) { 
    result = x == y; 
} 
else if (strcmp(op, "!=") == 0) { 
    result = x != y; 
} 

// now use result 
0

什么你实际上要求的是做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; 
    } 
    } 
} 
相关问题