Search code examples
c++c++17logical-operators

Can we use symbol in if statement in C++?


The user is asked to enter one of the following mathematical symbols:

+, -, *, or /

Can someone tell me how I can use these symbols in an if statement? If not, how can I do this without using an if statement, like 1 for addition, 2 for multiplication, etc?

if(z==+){
     std::cout<<x<<"+"<<y<<" is "<<x+y;
   }

Solution

  • The user inputting a value will typically be inputted as a char or string(depending on how you are reading it in. You cannot just compare a variable to a + sign on its own, it instead do something like this:

    if("+" == z) {
    //do operation
    }
    else if("*" == z) {
    //do operation
    }
    else {
    //etc.
    }
    

    or use switches.