Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my c++ course, I have been asked to generate a random number between 1 and 12 and add it to a sum. The program will ask if the user wants to add another number with the input y or n, and if the input is y it will add another number. When the sum reaches 50, the program will automatically end.
However, on lines 14 and 27, I get the error:
Expected a ;
And on line 16 I get the error:
identifier response is undefined
#include <iostream>
#include <iomanip>
using namespace std;
void rng(){
int rng = ((rand() % 12) + 1);
cout << rng;
}
int main()
{
int sum = 0
char response;
cout << "Would you like to add a number? y or n";
cin << response;
while (response = 'y') {
cout << "Would you like to add a number? y or n";
cin << response;
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
if (response = 'n')
cout << "Okay thanks, have a good one";
if (sum > 50)
cout << "Alright the sum has reached 50 that seems like enough"
break
};
}
There are a number of mistakes in your code - some related to syntax errors, and some related to logic issues.
Regarding the syntax errors:
int sum = 0
needs to be
int sum = 0;
A semicolon ends a statement.
cin << response;
needs to be
cin >> response;
operator<< is used for output, whereas operator>> is used for input.
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
needs to be
cout << "Okay then, the current sum is " << sum;
Using + on sum is redundant, but using + on rng is just plain wrong, since rng is a function, not a variable.
cout << "Alright the sum has reached 50 that seems like enough"
needs to be
cout << "Alright the sum has reached 50 that seems like enough";
Again, a semicolon ends a statement.
break
needs to be
break;
Again, a semicolon ends a statement.
Regarding the logic issues:
there is no need for #include <iomanip>, as you are not utilizing any stream manipulators.
you are missing #include <cstdlib> for rand().
rng() is a function, but the statement cout << ... << +sum << +rng; is trying to print it out as if it were a variable instead. The project requirement is to add the random number to the running sum, so rng() should return the number it generates, and then main() can add that number to sum before printing it out.
you are not calling srand() to initialize the random number generator before calling rand() the 1st time.
while (response = 'y') needs to be while (response == 'y'). operator= is for assignment, operator== is for comparison. That said, you should use a do..while loop instead, as there is no point in prompting the user twice on the 1st loop iteration.
if (response = 'n') needs to be if (response == 'n'). Again, assignment vs comparison. Also, you are also not break'ing the loop if the user enters 'n'.
if (sum > 50) is missing {} braces, so the subsequent break is not part of the if, and thus it will be invoked unconditionally after the 1st loop iteration is done, so the user will never be able to enter more than 1 number.
your cout statements should have \n or std::endl at the end of them, to print out a line break.
With that said, try something more like this instead:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rng(){
return (rand() % 12) + 1;
}
int main()
{
srand(time(NULL));
int sum = 0;
char response;
do {
cout << "Would you like to add a number? y or n: ";
cin >> response;
if (response == 'n') {
cout << "Okay thanks, have a good one\n";
break;
}
if (response == 'y') {
sum += rng();
cout << "Okay then, the current sum is " << sum << "\n";
if (sum > 50) {
cout << "Alright the sum has reached 50 that seems like enough\n";
break;
}
}
}
while (true);
}
This line:
int sum = 0
Needs a semi-colon at the end.
Same with these lines:
cout << "Alright the sum has reached 50 that seems like enough"
break
You need to use == instead of = in the condition of the while statement:
while (response == 'y') {
Also, this line:
cout << "Okay then, the current sum is" << +" " << +sum << +rng;
should be
cout << "Okay then, the current sum is" << " " << sum << rng;
Related
I am writing a program to very fundamentally simulate a black jack game using rand() % 11. We have to tell the players their running total as well as asking if they want another card (hit). My first problem is getting multiple random numbers and my second problem is not being able to add the two random numbers together. Strings are not allowed. Here's the block of code that I think is causing there's errors. I am very new to c++. Do I need to have multiple variables with the rand() %10 +1 to add them? I know that the add + add won't work but I can't figure out an alternative.
int add = rand() % 10 + 1;
bool hit = false;
int i = 0;
do {
cout << "Players 1 running total is " << add;
i++;
cout << " \n ";
cout << "Would you like another number? (0-yes or 1-no) ";
cin >> hit;
if ( hit == 0 ) {
cout << " You got an " << add << " \n ";
cout << "You're running total is " << add + add;
}
} while ( hit == false );
I assume this is an assignment given by an educator, otherwise, you shouldn't be using rand() at all (I don't blame you, I blame the instructor for not keeping up with the language.)
You must call rand() again to get a new number and use another variable to store the total:
Sidenote:
You should really declare your variables as close to first use as possible instead of the top of the program.
Also, The variable i isn't being used in this context so I removed it.
srand(time(0)); //Should be nullptr, but instructor probably doesn't know that.
int total = 0;
bool hit = false;
do {
int add = rand() % 10 + 1;
total += add;
cout << "\nYou got an " << add << " \n ";
cout << "\nPlayer 1 running total is " << total;
cout << "\nWould you like another number? (0-yes or 1-no) ";
cin >> hit;
} while (hit == false);
cout << "Player 1 final total is: " << total << endl;
// cai.cpp (Computer Assisted Instruction)
// This program uses random number generation to assist students learn multiplication
#include <iostream>
#include <iomanip>
#include <cstdlib> // contains prototypes for srand and rand
#include <ctime>
#include <cctype>
using namespace std;
int main() {
int question();
string status;
int score{0};
cout << "\nThis program will present you with 10 multiplication problems\n"
<< "enter the correct answer after the prompt\n"
<< "Enter Y for YES and N for NO\n"
<< "Do you want to try a game?";
cin >> status;
while(status == "Y" || status == "y") {
for(int x{0}; x < 11; x++) {
question();
score = score + question();
}
// report total score
cout << "\nTotal score is " << score << " out of 10";
cout << "\nWould you like to play again?";
cin >> status;
if(status == "n" || status == "N") {
break;
}
}
cout << endl;
}
int question() {
string responses();
// use srand to generate the random nmber for the various problems
srand(static_cast<unsigned int> (time(0)));
int number1 = 1 + rand() % 12; // initialize random number
int number2 = 1 + rand() % 12; // initialize random number
int total = number1 * number2;
int response;
int score{0};
cout << "\nWhat is " << number1 << + " times " << + number2 << + " ?";
cin >> response;
while (response != total) { // while answer is wrong, repeat question and wait for response
cout << " \nThat is incorrect, try again: ";
cin >> response;
}
if ( response == total) {
cout << responses();
score++; // increment score after each correct answer
}
return score;
}
string responses() {
string res1 = "Well done, that is correct!\n";
string res2 = "Congratulations, that is very accurate!\n";
string res3 = "Wow!, I'm impressed\n";
string res4 = "You're doing great! Keep up the good work.\n";
srand(static_cast<unsigned int> (time(0)));
int select{1 + rand() % 4};
switch(select) {
case 1: return res1;
break;
case 2: return res2;
break;
case 3: return res3;
break;
case 4: return res4;
break;
default: return " ";
}
}
When I compile and run this program, I expect it to loop only 10 times but it loops more than 10 times, I'm thinking it has to do with the switch statement in the responses function but I do not understand why it should be causing a problem. Any explanation would be greatly appreciated. I have modified the while loop condition in the main function to loop different times but it always loops to display all the possible responses in the switch statement. Screen shot of results attached, I modified the while statement to loop only twice but I still had all my responses showing so it ended up looping 4 times.
expect it to loop only 10 times but it loops more than 10 times
In your loop:
for(int x{0}; x < 11; x++)
x goes from 0 to 10, so it loops 11 times.
A few things to note. Your for loop goes up to < 11, meaning 10. So x from 0 to 10 (inclusive) is actually 11 times. You need to change the condition to < 10, or change x to start at 1.
Second issue, inside the for loop, you are actually calling the question function twice; with the first call's result being ignored. This is why you are getting 4 questions, each answered correctly, but only a score of 2.
Third, not so much an issue, but a bit redundant. At the end of the while loop, you check status == "n" || status == "N", however, this is unnecessary, since the while loop's condition checks for y and Y already.
I've cleaned up your while loop a bit here:
while(status == "Y" || status == "y") {
for(int x = 0; x < 10; ++x) {
score += question();
}
// report total score
cout << "\nTotal score is " << score << " out of 10";
cout << "\nWould you like to play again?";
cin >> status;
}
Unrelated thing to also clean up. You don't need to call srand in the question() function, instead just call it once in main. Also, since this is C++, you can use newer random generators from the <random> header.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Warning: I am brand new to programing! I am trying to create a random letter generator game for a class project. I feel like I have a decent start to it but I am having difficulty with a few points.
The program is supposed to ask the player how many games they would like to play(1-5). The maximum number of guesses they get per game is 5 and then it is supposed to print out what the correct answer was if it was not guessed. As it is, I have it so that it will run the correct number of guesses but not games and it dosent cout<< the correct answer when all guesses are done. Any help is appreciated, thanks.
#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
char alphabet [27];
int number_of_games;
char guess;
int x = 1;
srand(time(0));
int n = rand() % 26 + 1;
cout<<"Weclome to the Letter Guessing game!\n";
cout<<"You have 5 chances to guess each letter.\n \n";
cout<<"How many games do you want to play?\n";
cin >> number_of_games;
cout<<"**************************************************\n\n";
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
if (number_of_games < 1)
{
cout<< "Lets play game " << number_of_games << '\n';
}
//cout << (char)(n+97); //cheat to make sure working
cout<<"Enter your guess: ";
cin >> guess;
int guessValue = int(guess);
if (guessValue > (n+97))
{
cout<<"The letter you are trying to guess is before " <<guess <<"\n";
}
else if (guessValue < (n+97))
{
cout<<"The letter you are trying to guess is after " <<guess << "\n";
}
else if( (char)(n+97))
{
cout << "The answer you were looking for was " << (char)(n+97) << "\n";
}
else
{
cout<<"Your guess is correct! \n";
break;
}
//if answer is not right after x tries, cout the correct answer
x++;
}
system("pause");
return 0;
}
You can use "nested loops" - an outer loop for games, and an inner loop for turns. I've used a for loop in my example.
Also, no need to convert everything to int. char is an integral type and can be used just like a number:
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
// Select a new char (a-z) for each game
char n = 97 + rand() % 27;
cout << "Lets play game " << x << '\n';
// 5 guesses
for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
cout << "Enter your guess: ";
cin >> guess;
if (guess > n)
{
cout << "The letter you are trying to guess is before " << guess << "\n";
}
else if (guess < n)
{
cout << "The letter you are trying to guess is after " << guess << "\n";
}
else
{
cout << "Your guess is correct! \n";
// Break out of the inner for loop, not the while
break;
}
}
x++;
}
This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Well, I'll introduce myself first. I'm Ben, a 17-years old 'game-programmer' from the Netherlands who just has begun to program in C++ (started about a month ago, but programming for a year right now) (and I'm using Microsoft Visual Studio 2012 as compiler). Now, I am 'learning it myself' but I still do use a book and that book is called 'Beginning C++ Through Game Programming, Third Edition' by Michael Dawson.
I just did finish with chapter two and the last excersize was: "Write a new version of the Guess My Number program in which the player and the computer switch roles. That is, the player picks a number and the computer must guess what it is."
Here follows the code of the 'Guess My Number' Program:
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > secretNumber)
{
cout << "Too high!\n\n";
}
else if (guess < secretNumber)
{
cout << "Too low!\n\n";
}
else
{
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
Now, I was busy with thinking, programming testing and it just wouldn't work.
It seems I got stuck with such a infinite loop. But I can't find the problem.
Here's the code, and other ways to fix this are welcome, just keep in mind that I don't know a lot of the language. ;)
// Guess My Number 2
// The classic number guessing game with a twist
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
int secretNumberComputer = rand() % 100 + 1;
int secretNumberPlayer;
int triesPlayer = 0;
int triesComputer = 0;
int guessPlayer;
int guessComputer;
int tooHighPlayer;
int tooLowPlayer;
int correctPlayer;
int tooHighComputer;
int tooLowComputer;
int correctComputer;
int selectNumberIncorrect;
int lowerGuessComputer = 101;
int higherGuessComputer = 0;
cout << "Welcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guessPlayer;
++triesPlayer;
tooHighPlayer = (guessPlayer > secretNumberComputer);
tooLowPlayer = (guessPlayer < secretNumberComputer);
correctPlayer = (guessPlayer == secretNumberComputer);
if (tooHighPlayer)
{
cout << "Too high!\n\n";
}
else if (tooLowPlayer)
{
cout << "Too low!\n\n";
}
else if (correctPlayer)
{
cout << "\nThat's it! You got it in " << triesPlayer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctPlayer);
cout << "Now it's time for you to pick a number and then the computer will guess.\nEnter a number between 1 and 100: ";
do
{
cin >> secretNumberPlayer;
selectNumberIncorrect = (secretNumberPlayer > 100 || secretNumberPlayer < 1);
if (selectNumberIncorrect)
{
cout << "\nHey, that isn't a number between 1 and 100! Please pick a number that is: ";
}
else
{
break;
}
} while (selectNumberIncorrect);
guessComputer = (rand() < lowerGuessComputer && rand() > higherGuessComputer);
cout << "\n\nNow the computer is going to try to guess your number:" << endl;
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
tooHighComputer = (guessComputer > secretNumberPlayer);
tooLowComputer = (guessComputer < secretNumberPlayer);
correctComputer = (guessComputer == secretNumberPlayer);
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
}
else
{
cout << "Error, check code!\n\n";
}
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
if (triesComputer < triesPlayer)
{
cout << "You lost against the computer!\n\n";
}
else if (triesComputer > triesPlayer)
{
cout << "You won!\n\n";
}
else
{
cout << "It's a tie!\n\n";
}
cout << "Thank you for playing! Goodbye!" << endl;
return 0;
}
In this block you aren't checking the computer's guess for correctness (assigning correctComputer), so the loop continues forever, unless it guessed correctly the first time.
do
{
cout << "Computer, take a guess: " << guessComputer << endl;
++triesComputer;
if (tooHighComputer)
{
cout << "Too High!\n\n";
guessComputer = lowerGuessComputer;
}
else if (tooLowComputer)
{
cout << "Too Low!\n\n";
guessComputer = higherGuessComputer;
}
else if (correctComputer)
{
cout << "\nThat's it! You got it in " << triesComputer << " guesses!\n\n";
break;
}
else
{
cout << "Error, check code!\n\n";
break;
}
} while (!correctComputer);
Your second do loop never recalculates the computer's guess.
i.e. you have the computer guess one number before the do loop, then in the loop you keep checking if that one guess is too high or too low, never recalculating its value. It'll obviously never end.
You need to do the computer's guess calculation inside the second loop.
EDIT
Also, this logic is incorrect:
lowerGuessComputer = (rand() % 100 + 1 && rand() < guessComputer);
higherGuessComputer = (rand() % 100 + 1 && rand() > guessComputer);
The guess will always be 0 or 1 because the result of the right-hand-side operation is a boolean. In fact, I don't know what you're trying to do there. You're performing && between an integer and a boolean. I also don't understand why you are calculating two different guesses - you should calculate one number within the range of the higher/lower parameters you were given.
In addition to what Kevin Tran wrote, please check the valid input type for cin.
Imagine someone typing characters instead of integers.
so
cin >> guessPlayer;
can be written as
if (cin >> guessPlayer) {
// Do you logic here
}
else {
cout<<"Enter numbers only. :)";endl;
continue;
}
Hope this helps.
Instead of analyzing the code you posted which has numerous flaws, let's just think about what your program has to do: The user will pick a random number, and the computer will try to guess that number.
So, your program flow should go like this:
The computer picks a random number. It prints it out and asks the user to choose if the number is too high, too low or correct. (i.e. by asking the user to type '1' if too high, '2' if too low or '3' if it's right).
If the user types '3' then obviously you're done.
If it's too high, the computer picks a new random number (smaller than it's last guess) and tries the above logic again.
If it's too low, the computer picks a new random number (greater than it's last guess) and tries the above logic again.
Now let's try and implement some code that implements the above:
using namespace std;
int main()
{
int range_low = 0; // The number the user picked is greater than this
int range_high = 100; // The number the user picked is smaller than this
srand(static_cast<unsigned int>(time(0)));
do
{
// We want to generate a random number between range_low and range_high. We do this
// by generating a random number between zero and the difference of "low" and "high"
// adding it to low and adding one more.
int guess = range_low + ((rand() % (range_high - range_low)) + 1);
cout << "I'm guessing your number is " << guess << "... how did I do?" << endl
<< " [1: too high, 2: too low, 3: you got it!] ";
// Now let's see how we did...
int choice;
cin >> choice;
if(choice == 3)
{
cout << "Be amazed at my psychic powers! For I am a computer!" << endl;
break;
}
if(choice == 2)
{
cout << "Hmm, ok. I was sure I had it. Let's try again!" << endl;
range_low = guess;
}
if(choice == 1)
{
cout << "Really? Ok, ok, one more try!" << endl;
range_high = guess;
}
} while(true);
return 0;
}
Here are two exercises for you to improve the above:
First, try to compare the logic of this code against the logic of your code and see where your code differs - try to understand why it was wrong. It will help to try to execute the program using pen and paper, just like you were a computer that understood C++.
Second, try to add code to ensure that the computer never guesses the same number twice.