Question about String Guess = "";

Hello there,

I was trying to find similar question about this statement, but wasn’t unable to locate on. Still, I am sorry for posting this again in case this question has been answered somewhere already.

String Guess = “”;

Can someone explain me why are we giving value to the variable Guess in Lection 22. - Variables and cin for Input? (I hope I properly addressed what is the variable and what is the value in this example :slight_smile:).

Parallel with the udemy lessons I started reading the tutorial for c++ on www.learncpp.com. And if I understood correctly, if we state variable in our code, we are basically assigning memory slot to it. And we can always put value to it latter in the code, which we did in this statement:

cin >> Guess;

The value should be players input in console, right? Please correct me if I am wrong. This is my way of learning, asking question where I fail to see logic.

Until player gives an input, variable Guess in an uninitialized variable, am I right?

I tried running the code with and without giving it a variable (String Guess; and String Guess = “”:wink: and I got the same output.

Can someone explain me why was important assigning “empty” value to the string Guess;?

Just for the context of the question here is the part of the code I am talking about:

//get a guess from player
cout "Enter your guess: ";
string Guess = “”;
cin >> Guess;
cout << "Your guess wass: " << Guess;

Hi, I have not yet done that many lectures of this course. But I might able to help you out a tad.

I would argue that a initial value is set in order to get rid of the random bits of memory other wise assigned to it if used before a value is set by the user( so that you can predict the behavior of this variable)

By doing this you have for instance say

if (!Guess) {
   cout << "would you like to enter a guess?\n";
   
} else {
   cout << "A guess has been made already\n"; 
}

By having guess set to Guess = “”;
The value of Guess will be 0 and therefor enter the if part of the statment

You can see a longer explanation here: http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/

I believe I get it now. Thank you for your explanation!

Privacy & Terms