1

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.

  • what is the data type of response? – Sujil Maharjan Jan 31 '18 at 20:33
  • Assuming this properly compiled (because `response` is a `char`), the problem lies with `playOneGame()`. Make sure that you completely reset the game state so that `playOneGame()` doesn't still think the game is over. – Dúthomhas Jan 31 '18 at 20:38

3 Answers3

2

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;
}
djs
  • 1,660
  • 1
  • 17
  • 35
0

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.

O Dundar
  • 90
  • 1
  • 6
0

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?

Yves
  • 11,597
  • 17
  • 83
  • 180