字符到运算符 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13142270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:01:08  来源:igfitidea点击:

Char to Operator C++

c++charoperators

提问by wzsun

Hey I wanted to know how you could turn a character '+' into an operator. For example if I had

嘿,我想知道如何将字符“+”转换为运算符。例如,如果我有

char op = '+'
cout << 6 op 1;

Thanks.

谢谢。

回答by john

SImple way is to use a switch statement

简单的方法是使用 switch 语句

switch (op)
{
case '+':
  res = x + y;
  break;
case '-':
  res = x - y;
  break;
case '*':
  res = x * y;
  break;
}

回答by Dan

I don't think there's a way as you've written it there but you could do something hacky like

我不认为有你在那里写的方法,但你可以做一些像

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")
    }
 }

回答by argothiel

You may use an old-way #define:

您可以使用旧方式#define:

#define op +
std::cout << 6 op 1;

However it has limited use.

然而,它的用途有限。

If you want to do this in pure C++, you will have to use switch syntax either explicitely or in an external library (like tetzfamily.com/temp/EvalDoc.htm or codeproject.com/Articles/7939/C-based-Expression-Evaluation-Library)).

如果您想在纯 C++ 中执行此操作,则必须明确地或在外部库中使用 switch 语法(如 tetzfamily.com/temp/EvalDoc.htm 或 codeproject.com/Articles/7939/C-based-Expression-评估库))。

Another way is to use an external program, like bc:

另一种方法是使用外部程序,例如 bc:

char op = '+';
std::string s;
s += "6";
s += op;
s += "4";
system(("echo " + s + "|bc").c_str());

If you want to use the result later, check the popenfunction or the C++ equivalent.

如果您想稍后使用结果,请检查popen函数或C++ 等效项

回答by user2722684

public class ArithmeticOps {

   static int testcase11 = 11;
   static int testcase12 = 3;
   static char testcase13 = '/';

   public static void main(String args[]){
        ArithmeticOps testInstance = new ArithmeticOps();
        int result = testInstance.compute(testcase11,testcase12,testcase13);
        System.out.println(result);
   } 


public int compute(int a, int b,char operator){
    int i=0;
    switch(operator)
    {

    case '+' :
        i= a+b;
        break;
    case '-' :
        i= a-b;
        break;
    case '*' :
        i= a*b;
        break;
    case '/' :
        i= a/b;
        break;
    case '%' :
        i= a%b;
        break;
    case '^' :
        i= a^b;
        break;
    default:
        i=0;
    }
    return i;


}

}

}