dillib
dillib

Reputation: 357

Issue with loop repeating one more time than it should

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main()
{
    char terminate;
    double a, b, answer;
    char operators;

    cout << "Please enter your expression: ";
    terminate = cin.peek();
    cin >> a >> operators >> b;

    while (terminate != 'q')
    {
        switch(operators)
        {
            case '+':
                answer = a + b;
                break;
            case '-':
                answer = a - b;
                break;
            case '*':
                answer = a * b;
                break;
            case '/':
                answer = a / b;
                break;
            case '^':
                answer = pow(a,b);
                break;
        }

        cout << a << " " << operators << " " << b << " = " << answer << endl;

        cout << "Please enter your expression: ";
        cin.clear();
        terminate = cin.peek();
        cin >> a >> operators >> b;
    }

    return 0;
}

This is my simple calculator program, it is meant to repeat and ask the user to enter a binary expression until the value "q" is entered, however upon entering "q" the while loop still executes once more even though the variable terminate has the value of "q". I don't understand why it is doing this, any help would be appreciated. Thanks

Upvotes: 1

Views: 133

Answers (1)

Caesar
Caesar

Reputation: 9841

Let us take a look at an example of what is happening with this input:

1 + 1 Enter

terminate = cin.peek();

This line will peek into the buffer, read what is there but it will not remove it from the buffer

cin >> a >> operators >> b;

This line will read 1 + 1 and store it in a operators b and remove those characters from the buffer

Now what you have left is the Enter key which is still in the buffer and it will be read the next time you try and read the buffer and this is where you issue is as the next time you call terminate = cin.peek(); you get the \n and not the q that you expect

I noticed that you might have tried to fix that issue by calling std::cin::clear but that is not what that function does. That functions resets the iostate flags and that is not what you are looking for. If you want to clear the buffer then you have to call std::cin::ignore

Upvotes: 1

Related Questions