Section 2 Lecture 21: Console shows "Ask to play again?" twice?

Hi,

I must be missing something really obvious but from what I can see, my code is quite similar to Ben’s (not identical) and it asks to play again twice, not once, when I run it in the console.

My code is as below. Apologies for not using code formatting, I don’t see any options in the text box.

#include <iostream>
#include <string>

using namespace std;

void PrintIntro();
void PlayGame();
string GetGuess();
bool AskToPlayAgain();


int main() 
{
	do
	{
		PrintIntro();
		PlayGame();
		AskToPlayAgain();
		//cout << AskToPlayAgain();
	} while (AskToPlayAgain() == true);
	
	return 0;
}


void PrintIntro() 
{
	// introduce the game
	constexpr int WORD_LENGTH = 9;
	cout << "Welcome to Bulls and Cows, an amazing word game\n";
	cout << "Can you guess the " << WORD_LENGTH;
	cout << " letter isogram I am thinking of?\n";
	cout << endl;
	return;
}


void PlayGame()
{
	constexpr int NUMBER_OF_TURNS = 5;
	for (int i = 1; i <= NUMBER_OF_TURNS; i++)
	{
		//cout << "Enter Guess " << NUMBER_OF_TURNS;
		cout << endl;
		string Guess = "";
		Guess = GetGuess();
		cout << "Player guessed " << Guess << endl;
		cout << endl;
	}
}

// get a guess from player
string GetGuess() {
	cout << "Enter your guess: ";
	string Guess = "";
	getline(cin, Guess);
	//cin >> Guess;
	return Guess;
}

bool AskToPlayAgain()
{
	cout << "Do you want to play again?";
	string Response = "";
	getline(cin, Response);
	return (Response[0] == 'y') || (Response[0] =='Y');
	
}
1 Like

Remove this in int main():
AskToPlayAgain();

So you int main() looks like this (I commented it):

1 Like

Works like a charm! Thank you!

Is that because the do while loop executes once anyway so if I call the function in there, it shows up twice?

A bit late to answer your question rak10, but it’s actually because AskToPlayAgain() is being called twice in your example. Once in the main body of the do (while) loop, and AGAIN in the while portion. Having the function inside the while() will still run that function once the program gets down to it. It isn’t because of the nature of the do(while) loop executing once anyway.

I am equally late in replying to you, but thank you. Yes, that was indeed the problem.

Privacy & Terms