Code is not working

OK: my code is not working. An explanation of what I want it to perform is at the bottom of my code.


#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
int secretNumber;
cout << "Type your number here.";
cin >> secretNumber;

int guess;

do
{
srand(static_cast<unsigned int>(time(0)));
int guess = rand();
cout << "Is it " << guess << endl;

if (guess < secretNumber)
{
cout << "\n\nOk I have to guess lower...";
}
else if (guess > secretNumber)
{
cout << "\n\nOK I have to guess Higher...";
}
else
{
cout << "\n\nYes I got it!";
}
}while (guess == secretNumber);

system ("pause");
return 0;
}


Basically, I am making a program where the computer tries to guess the number that I type in. There are no compiler errors, but when I run the program, It does not stop and only guesses the same number.

for example: Is it 34567. OK I have to guess lower... (and so on)

Basically it keeps repeating what it has already done. Is there a solution to this?

Thank you.
Use srand ONCE.

You're using it every time in the loop, and each time it sets the sequence of nubmers that rand will give you back to the start, so you get the same number each time you call rand.
No, that did not fix it.
The guessing game is rather pointless if you choose a new number before every guess.
Why are you doing that?

Your while condition is messed up as well (besides accessing an uninitialized value). Review the structure of a do-while loop.
Last edited on
Ya... I dont understand my code fully. Im trying to do one of the exercises in my book an so i am experimenting. Are you referring to the part with the srand? Because I took that out of the loop and put it under int guess;
Sorry for wasting your time. I just figure out why it was repeating. I had to take out int guess = rand(); of the loop as well. thank you for helping me figure this out.
Topic archived. No new replies allowed.