### program that will guess which number the user is thinking of

Hello! I'm trying to get a program to work that will guess which number the user is thinking of, however it currently only outputs the same number each time. Please tell me what I've done wrong? Thank you!

 ``1234567891011121314151617181920212223242526272829303132333435`` ``````srand(time(0)); int lowernum = 1; int highernum = 1000; int number=rand()%highernum + lowernum; string letter = ""; int letternum = 0; cout<<"\nOkay, think of a number between one and 1000 and I will try to guess it!\n"; cout<<"\nIs your number higher (h), lower (l) or exactly (e): " << number << "\n"; cin>>letter; if (letter == "h") { letternum = 1; } else if (letter == "l") { letternum = 2; } else if (letter == "e") { letternum = 3; } switch(letternum){ case 1: highernum = number; cout<<"\nIs your number higher (h), lower (l) or exactly (e): " << number << "\n"; cin>>letter; break; case 2: lowernum = number; cout<<"\nIs your number higher (h), lower (l) or exactly (e): " << number << "\n"; cin>>letter; break; case 3: cout<<"\nWahoooooo! I win! :D\n"; break; default:cout<<"\nI don't understand what you just typed in.\n"; break; }``````
Last edited on
I think you want your cases to look like this:

 ``1234`` ``````case 1: number = highernum; cout<<"\nIs your number higher (h), lower (l) or exactly (e): " << number << "\n"; cin>>letter; break; case 2: number = lowernum; cout<<"\nIs your number higher (h), lower (l) or exactly (e): " << number << "\n"; cin>>letter; break;``````

This way, number will be either 1 or 1000 after the switch block. The way you have it, both number and highernum, or number and lowernum will be the randomly generated number.
Your if and switch statements need to be inside of a loop that will run until the number is guessed. You also really shouldn't have your cout and cin statements for the number being higher, lower, or correct more than once. Also, I'm fairly certain that you can do switch statements with characters, so you don't need those if statements to convert to decimal. Instead it would be
 ``12345678910111213141516171819`` ``````// output your first line (the greeting) before the loop while (!guessed) // or guessed == false, these are equivalent { number=rand()%highernum + lowernum; // output the rest of it inside the loop cin >> letter; switch (letter) { case "h": highernum = number; break; case "l": lowernum = number; break; case "e": // output victory statement guessed = true; break; default: // incorrect input }``````

Lastly, there's little reason for letter to not be a character rather than a string. If you make this change, just replace all of the uses of double quotes (other than in cout statements) with single quotes.

Edit: I forgot that you're probably intending to generate a new random number to guess each time. I update the code to include that.
Last edited on
Topic archived. No new replies allowed.