Hi,
I would like to introduce a different approach of implementing the error message handling (invalid word length, not an isogram, etc…).
In C++ there is a way in returning multiple values from a function - here we want to return the error enum and the error message - using Tuples.
-
First: We will use “tuple header file”
#include <tuple>
-
Second: We will modify our
checkGuessValidity()
function declaration in FBullCowGame.h into
std::tuple<EWordStatus, FString> checkGuessValidity(FString) const;
this means we want the function to return two values - the error enum and the error message - -
Third: for the function implementation I modified it like this:
std::tuple<EWordStatus,FString> FBullCowGame::checkGuessValidity(FString guess) const {
//if it is invalid word length return std::make_tuple(EWordStatus::Wrong_Length, "ERROR invalid word length!");
//if it is not isogram return std::make_tuple(EWordStatus::Not_Isogram, "ERROR word is not
//else return OK return std::make_tuple(EWordStatus::OK, "OK"); }
the key line here is example return std::make_tuple(EWordStatus::OK, "OK");
to return multiple values we use make_tuple()
function and pass arguments inside
-
Finally: In the main.cpp, I modified both
validGuess()
andplayGame()
functionsFText validGuess() { FText guess = ""; FText wordStatusMessage = ""; EWordStatus wordStatus = EWordStatus::Invalid; `` while(wordStatus != EWordStatus::OK) { guess = getGuess(); tie(wordStatus, wordStatusMessage) = BCGame.checkGuessValidity(guess); if (wordStatus != EWordStatus::OK) std::cout << wordStatusMessage << std::endl; } return guess; } `` void playGame(FString guess) { int32 maxTries = BCGame.getMaxTries(); `` for (int32 i = 0; i < maxTries; i++) { FBullCowCount bullCowCount = BCGame.SubmitGuess(guess); std::cout << "Bulls = " << bullCowCount.Bulls; std::cout << " Cows = " << bullCowCount.Cows << std::endl; std::cout << "Your guess was: " << guess; } }
The modified implementation is that we declare 3 variables in validGuess()
function; the word, the enum error and the error message.
We use the function tie()
to assign multiple returned values to our multiple variables tie(wordStatus, wordStatusMessage) = BCGame.checkGuessValidity(guess);
We keep looping calling checkGuessValidity()
function till the value of enum error is OK, and we pass the guessed word to the next function which is playGame()
in the main function.
int main()
{
bool bWantToPlayAgain = false;
do
{
printIntro();
playGame(validGuess());
bWantToPlayAgain = askToPlayAgain();
} while (bWantToPlayAgain);
return 0;
}
I hope you find this topic useful, happy coding everyone