I came up with another solution to this challenge, which went through making another function to print the guess. The problem I have with this is that every variation of this solution I come up with carries some problems. My base solution was this:
#include <iostream>
#include <string>
using namespace std;
void PrintIntro();
void PlayGame();
string GetGuess();
void PrintGuess(string Guess);
int main() {
PrintIntro();
PlayGame();
return 0;
}
void PlayGame()
{
//Loop for number of turns
constexpr int TURNS = 5;
for (int i = 0; i < TURNS; i++) {
PrintGuess(GetGuess());
}
}
void PrintIntro() {
constexpr int WORD_LENGTH = 5;
cout << "Welcome to Bulls and Cows game" << endl;
cout << "let's see if you can guess my " << WORD_LENGTH << " letter isogram\n";
return;
}
string GetGuess() {
string Guess = "";
//Get guess form player
cout << "Enter your guess: ";
getline(cin, Guess);
return Guess;
}
void PrintGuess(string Guess)
{
//Print the player's guess
cout << "Your guess was: " << Guess;
cout << endl << endl;
return;
}
However, in this I see a problem if you need the returned value (the guess) for another function/action, since with this method, that returned value is lost.
An alternative to this is to store the value in the variable âGuessâ and then call it with as many functions as you need, something like this:
void PlayGame()
{
//Loop for number of turns
constexpr int TURNS = 5;
for (int i = 0; i < TURNS; i++) {
string Guess = GetGuess();
PrintGuess(Guess);
}
}
But for this, you need to declare the variable âGuessâ either in PlayGame() or as a global variable. These two options both carry problems: declaring it in PlayGame() makes it inaccesible for the function GetGuess(), while defining it as global may grant unwanted access from other functions.
If it is declared in PlayGame(), a second variable (for example âstring Guess2â) could be declared in GetGuess() to allow for functioning, but then youâre increasing the memory used by the program as youâre declaring and using more variables.
The final solution I though is doing a double declaration of the variable âGuessâ, but then, the previous value of the variable âGuessâ would be lost. While this is not a problem in this case, in the case, for example, of concatenating strings, it would become a problem.
Any input on what the best path would be?
If you have reached here, thanks.