Roemerdt
Roemerdt

Reputation: 147

c++ calculator keeps looping

I made this calculator

#include <iostream>

using namespace std;

int main()
{
    float a, b, result;
    char operation;

    while (1) {

        cout << "Enter the calculation you want to perform (e.g: 1 + 2)\n>>";
        cin >> a >> operation >> b;

        switch(operation)
        {
            case '+':
                result = a + b;
                break;

            case '-':
                result = a - b;
                break;

            case '*':
                result = a * b;
                break;

            case '/':
                result = a / b;
                break;

            default:
                cout << "\nInvalid operation. Program terminated." << endl;
                return -1;
        }

        cout << "= " << result << "\n" << endl;
    }

    return 0;
}

It's supposed to keep asking the same question and terminate if you enter something invalid.

If you enter something invalid the first time it terminates. But if you enter a valid operation and the second time you enter a invalid character it keeps outputting the same question + answer that it handled before the invalid character.

Upvotes: 1

Views: 2647

Answers (3)

MASL
MASL

Reputation: 949

Just adding the line

operation=0;

right after the while(1) will do the job of terminating when an invalid answer is provided.

However, this doesn't explain why without it, the program skips asking for an operation and keeps outputting the previous result when an invalid answer is provided.

Upvotes: 0

Maksim Solovjov
Maksim Solovjov

Reputation: 3157

By default, when a stream fails to read something, it will set its internal failbit on and it will leave the input it could not parse untouched. So, when you provide the input "x = 2" to your code and then try to read x as an integer, the reading fails and x remains in. Whatever happens afterwards will probably be wrong, and it will be wrong in many different ways depending on an input.

To defend against that, check whether the input succeeded:

    cin >> a >> operation >> b;

    if (!cin) {
        cout << "Wrong input format. Program terminated.\n";
        return -1;
    }

In your particular case, the particular behaviour you was getting was because you did not reinitialise your variables at every iteration of the loop. If you did that, your application would fail in some different fashion, but nonetheless, the best way out is to actually check whether the input was in the expected format.

Upvotes: 3

Jordy Baylac
Jordy Baylac

Reputation: 550

that's because of "operation" var is out of the "while" scope, i.e the last value is verified and the default body on the switch is never verified

Upvotes: 0

Related Questions