Home > Back-end >  How to compare a symbol typed in by a user with another symbol?
How to compare a symbol typed in by a user with another symbol?

Time:12-26

I've tried with comparing char variable with a symbol in "" and it sais:

ISO C   forbids comparison between pointer and integer [-fpermissive]

Here is full code:

#include <iostream>

int main(){
    int a, b;
    char c;
    std::cin >> a >> c >> b;
    if (c == " "){
        std::cout << (a   b);
    }
    if (c == "-"){
        std::cout << (a - b);
    }
    if (c == "*"){
        std::cout << (a * b);
    }
}

What should I do?

CodePudding user response:

"c" results in a character array or what we call a C-string, which is not what you want. If you want to have an expression which represents a single character use 'c' instead!

The code becomes:

#include <iostream>

int main(){
    int a, b;
    char c;
    std::cin >> a >> c >> b;
    if (c == ' '){
        std::cout << (a   b);
    }    
    if (c == '-'){
        std::cout << (a - b);
    }    
    if (c == '*'){
        std::cout << (a * b);
    }    
}

As reading the other answer here: You should decide to use string to string compare or character to character compare. Mixing it up will simply not work out of the box.

  •  Tags:  
  • c
  • Related