My solution for lecture 23, its working, but is it a good way?

Hey there. I just started this course, and so far I am having a blast. For the first time though, I have a different solution that seems to be working. Can I get any feedback on it? This is my solution:

bool askPlayAgain()
{
	cout << "Play again?";
	string feedback = "";
	getline(cin, feedback);
	bool playAgain = "";
	playAgain = (feedback[0] == 'y' || feedback[0] == 'Y');
	return playAgain;
}

So instead of return (the comparison here) I put it in a variable first, then I return it. I am used of doing it like this in Game Maker Studio.

Also I do the comparison like that, while the tutor does it like this: (feedback[0] == β€˜y’) || (feedback[0] == β€˜Y’);

Is there any difference that I dont know about? Cheers!

1 Like

im not sure if it is recommended or not, im a beginner.
That said, i really like your code and it made my program run better imo.

i was having issues trying to get the game recognize the assignment of a bool from a function for example

bool bPlayAgain = AskToPlayAgain();
do
    {
	    PrintIntro();
	    PlayGame();
    } while (bPlayAgain == true);
    return 0;

This didnt work the way i intended.
I changed my AskToPlayAgain() function

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

Now in main()

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

Works like a charm :slight_smile:

2 Likes

In this particular case moving parentheses makes no difference - either way is fine.

Also note that you assigned an empty string to a boolean variable:
bool playAgain = "";

Use true or false instead, e.g.

bool playAgain = false;

I agree with OldDauber. The logic is effectively the same either way. One good way to answer this logic question for yourself is to visualize what the lines are actually saying and say the logic out loud. If it makes sense out loud, then it usually works in code.

And another neat trick to initialize your playAgain variable:

Instead of going:

bool playAgain = false;
playAgain = (feedback[0] == 'y' || feedback[0] == 'Y');

Combine the lines like this:

bool playAgain = (feedback[0] == 'y' || feedback[0] == 'Y');

This is a quick and dirty method of initializing one time use variables.

1 Like
int main()
{
	do
	{
		PrintIntro();
		PlayGame();

	} while (AskToPlayAgain());

	return 0;
}
bool AskToPlayAgain()
{
	cout << "Would you like to play again?(y/n) ";
	string Response;
	getline(cin, Response);

	return (Response[0] == 'y') || (Response[0] == 'Y');
}

I like this style because it is simple and readable easier. Just remember, 0 is false, otherwise is true. So if the bool AskToPlayAgain doesn’t return (Response[0] == β€˜y’) || (Response[0] == β€˜Y’), it means it will return false.

Privacy & Terms