Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert char to arithmetic operator

Tags:

c++

char

I have a char stand for an operator,there are four operators(+ - * /) in total.

How i did :

int Compute(char c, int a, int b)
{
    if(c == '+')  
        return a+b;
    else if(c == '-')     
        return a-b;
    else if(c == '*')
        return a*b;
    else (c == '/')
        return a/b;
}

Is there a more convenient way to do this?

like image 285
Superxy Avatar asked Jan 22 '16 10:01

Superxy


People also ask

Are arithmetic operators characters?

Character arithmetic is used to implement arithmetic operations like addition and subtraction on characters in C language. It is used to manipulate the strings. When the characters are used with the arithmetic operations, it converts them into integer value automatically i.e. ASCII value of characters.

Can you use a char as an operator in C?

I'm sorry, but you can't convert a char to an operator. If you want to take different actions depending on the input, you must branch. You can make your switch more compact though, as noted by Matteo Italia and Jens Gustedt.

Can char be a operator?

Yes - the user gives an input, which is a char or a String or something, which is interpreted as operator by your calculator.

How do you use character operator?

Another way is to use an external program, like 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.


1 Answers

You could use a switch statement:

int Compute(char c, int a, int b)
{
    switch (c) {  
    case '+': return a+b;
    case '-': return a-b;
    case '*': return a*b;
    case '/': return a/b;
    default: throw std::runtime_error("No such operator");
    }
}
like image 134
TartanLlama Avatar answered Sep 22 '22 20:09

TartanLlama