Search code examples
c++character-properties

Is there special syntax to follow when comparing chars in C++?


I've been learning C++, and I tried to create a basic calculator app. The goal is to obtain two numbers from 0-9 from the user, and a mathematical operation (+, -, *, /); if some other character is typed, I want to loop the program to keep prompting for the proper input.

But whenever I run the program, it doesn't recognize the numbers 0-9, and keeps repeating the loop. These are the main 3 functions I am using. From main, I'm simply calling them, so I doubt the problem is there. Help please?

Oh and I know I'm never supposed to use go-to, but I wanted practice. And if you could point out more efficient ways of writing this code, that's awesome. Thanks a million.

int GetUserInput(){
    using namespace std;
    cout << "Please enter a number between 0-9." << endl;
    
    char inputChar; 
    cin >> inputChar;

    while (inputChar != ('1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || '0')) {
        cout << "Please enter a number between 0-9." << endl;
        cin >> inputChar;
    }

    return static_cast <int> (inputChar);
}

char GetMathematicalOperation(){
    using namespace std;
    cout << "Please enter a mathematical operator (+, -, *, /)" << endl;

    // Storing user input character into char inputChar
    char inputChar; 
    
    inputloop:
    cin >> inputChar;
    switch(inputChar) {
        case('+'):
        case('-'):
        case('*'):
        case('/'):
            break;
        default:
            cout << "Please enter a mathematical operator (+, -, *, /)" << endl;
            goto inputloop;
        }

    return inputChar;
}

int CalculateResult(int x, char Operator, int y){
    if (Operator = '+')
        return x+y;
    if (Operator = '-')
        return x-y;
    if (Operator = '*')
        return x*y;
    if (Operator = '/')
        return x/y;
    return 0;
}

Solution

  • The || operator needs to operate on boolean expressions, which characters are not. You'd need to expand it out to while (inputChar != '1' && inputChar != '2' && ....

    Alternatively, you could exploit the fact that the character codes of digits are sequential. In other words, you could do while (inputChar < '0' || inputChar > '9').

    Also, in your CalculateResult function, you need to change those = to == - otherwise, you overwrite the Operator variable, rather than comparing to it.