My Solution Using a Ternary Operator

For those not familiar, a ternary operator is just an if statement condensed onto one line with the following syntax: Condition ? result if true : result if false. It allows assignments or returns to happen on a single line. With my use, it’s set up to return true if the user entered y or Y and false if they enter incorrect inputs or enter no. I considered placing a check in order to force a user to enter the correct input but decided against it for this project.

// Ask user if they wish to play again, return true or false accordingly.
bool PlayAgain()
{
	string response = "";
	char firstLetter;

	cout << "Do you wish to play again? (Yes/No): ";
	getline(cin, response);

	firstLetter = response[0];
	
	return (firstLetter == 'y' || firstLetter == 'Y') ? true : false; 
	// If the user enters anything except for y or Y, the program will return false.
}

Thanks for sharing.

Privacy & Terms