Is there a way that I can convert the operator as char "+" to the actual operator for arithmetic?

How would I convert char "+" to + to add? I'm trying to make the user enter the operator + - * / / then print the operator b.

I could just do a bunch of if statements, but wondered if there is a way to do this more efficiently?

if (operator == "+") {cout << a + b;} else if (operator == "-") {cout << a - b;} 

etc..

0
source share
4 answers

Use a switch assuming token is a char, where you get the operator, and op1 and op2 are 2 operands:

 switch (token) { case '/': val = op1 / op2; break; case '*': val = op1 * op2; break; case '+': val = op1 + op2; break; case '-': val = op1 - op2; break; } 
+3
source

You can use a map with function pointers.

 int addition(int a, int b){ return a + b; } std::map<char, int(*)(int, int)> operators; operators.insert(make_pair('+', addition)); char c = getch(); int first_operand = 10; int second_operand = 20; int result = operators[c](first_operand, second_operand); 
+1
source

In this case, it is better to use a switch. Otherwise, the solution seems good to me.

0
source

You can also use such a card, I do not think that the efficiency in this case is too great.

 cout << operators[op](a, b); 
0
source

Source: https://habr.com/ru/post/1241214/


All Articles