简体   繁体   English

Char to Operator C ++

[英]Char to Operator C++

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. 谢谢。

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;
}

I don't think there's a way as you've written it there but you could do something hacky like 我不认为有一种方法,因为你已经在那里写了但是你可以做一些像hacky这样的事情

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

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 ++中执行此操作,则必须明确使用切换语法或在外部库中使用(如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 popen function or the C++ equivalent . 如果要稍后使用结果,请检查popen函数或C ++等效函数。

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;


}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM