Simple functions problem

Hi. I'm very much a noob here. This code should be asking for a guess via the console, and then printing it back to them. It's not working as I would expect. Can someone please explain to me why this code is asking for the user to input a guess twice? I know it's basic but I really need to understand why this is happening with this code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

using namespace std;

void PrintIntro();
string GetGuess();
string PrintGuess();

// the entry point for our application
int main()
{
	PrintIntro();

	GetGuess();
	
	PrintGuess();

	cout << endl;
	return 0;
}

// introduce the game
void PrintIntro() {
		constexpr int WORD_LENGTH = 5; // constexpr means evaluated at compile time
	cout << "Welcome to Bulls and Cows, a fun word game." << endl << endl;
	cout << "Can you guess the " << WORD_LENGTH;
	cout << " letter isogram I'm thinking of?" << endl << endl;
	return;
}

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

// repeat the guess back to them
string PrintGuess() {
	string WriteGuess = GetGuess();
	cout << "Your guess was: " << WriteGuess << endl;
	return WriteGuess;
}
Can someone please explain to me why this code is asking for the user to input a guess twice?


Because you call it twice - once in main and once in PrintGuess.
It would make more sense when you pass the guess as a parameter to PrintGuess.
You're calling the GetGuess() function twice. Once on line 15, then again on line 43.
Last edited on
I think I see. Are you saying that my "string WriteGuess = GetGuess();" is where I call it again, rather than getting the value from GetGuess?

Edit: I get it now! Thank you very much Arslan!
Last edited on
Are you saying that my "string WriteGuess = GetGuess();" is where I call it again, rather than getting the value from GetGuess?


Yes, remember that the left side of the assignment statement is evaluated first.

So the line: string WriteGuess = GetGuess(); first calls the GetGuess() function, the assigns its return value to the string variable 'WriteGuess'.
Last edited on
Topic archived. No new replies allowed.