Jonas Manno
Jonas Manno

Reputation: 11

If you enter the desired input twice, it outputs twice?

Heres my example:

while (response == 'y')
{
    playOneGame();
    cout << "Great! Do you want to play again (y/n)? ";
    cin >> response;
}

And if you type in: yy

It prints the output twice:

"Great! Do you want to play again (y/n)? Great! Do you want to play again (y/n)? "

I would just like to understand why. This program is written in C++ if that matters. Thanks.

Upvotes: 1

Views: 105

Answers (3)

Yves
Yves

Reputation: 12381

This is exactly what you need. Apply the code below to your real case.

#include<iostream>
#include<limits>
using namespace std;
int main()
{
        char response = 0;
        while(cin >> response){
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "You enterd: " << response << endl;
        }
        return 0;
}

Here is the explanation:
Why would we call cin.clear() and cin.ignore() after reading input?

Upvotes: 0

O Dundar
O Dundar

Reputation: 90

It is not clear the type of response, but I assume it is char.

char response;

while(response=='y'){
    playOneGame();
    cout << "Great! Do you want to play again (y/n)? ";
    cin >> response;
}

cin reads all the chars until you stop sending chars to it. Simply, cin gets whole terminal line so when you press 'yy', while loop runs twice.

If loop runs twice and prints the message two times: 1. It doesn't start game again. 2. Even, it starts the game, when it is over, for the second y, it does starts game again without asking.

Modify your code to read one char and continue. You can use getche() to get one char and continue.

Upvotes: 0

djs
djs

Reputation: 1690

Since you are comparing it to a char (result == 'y'), I'm assuming result is also a char.

The cin operation is going just read one char, and leave the second one on the input buffer. Then, the next time through the loop, it reads the second 'y' without any additional user input required.

If you want to be sure there is nothing left in the buffer, read until you get a line terminator. Or you can read into a string:

string response = "y";
// continues on anything that starts with lowercase 'y'.
// exits on anything else.
while (response.length() >= 1 && response[0] == 'y') // length check maybe unnecessary?
{
    playOneGame();
    cout << "Great! Do you want to play again (y/n)? ";
    cin >> response;
}

Upvotes: 2

Related Questions