Guess-my-number Program

I'm trying to get a guess-my-number project to work, but attempting to get it to loop results in errors. Maybe my method of looping it doesn't work. Sorry, I'm an amateur at C++ programming, but I'm trying to learn.
Here's my source file:

//Guess my number!

#include <stdlib.h>
#include <iostream.h>
using namespace std;

int main()
{
srand((unsigned)time(0));
int random_integer;
int tries = 1;
int guess;
for(int index=0; index<20; index++)
random_integer = (rand()%10)+1;
cout << random_integer << endl;
cout << "I'm thinking of a random number between 1 and 10. Care to guess?" << endl;
cin >> guess;

if(guess == random_integer)
{
cout << "You're correct!" << endl;
cout << "It took you " << tries << " tries to guess the number!" << endl;
}
else if(guess == random_integer + 1)
{
cout << "You're close!" << endl;
tries + 1;
}
else if(guess == random_integer - 1)
{
cout << "You're close!" <<endl;
tries + 1;

}
else
{
cout << "Nope! Try again!" << endl;
tries + 1;
}
system("pause");
return 0;
}

When I guess the number wrong, I don't have another try on it. Basically, it doesn't loop when the number is guessed wrong, but I want it too until you get the correct number.
Last edited on
Right now, your only loop is
1
2
for(int index=0; index<20; index++)
    random_integer = (rand()%10)+1;

which just assigns a random integer to random_integer 20 times in a row (each time overwriting the previous value).

After that, you get an input from the user, compare it with a few values, and exit.

You need to loop around the code that gets the input and prints the messages, not the code that generates the random number.
It should suffice to put a do { before the cin >> guess; and a } while (guess != random_integer); after the
1
2
3
4
5
else
{
    cout << "Nope! Try again!" << endl;
    tries += 1;
}
.

On a side note, what compiler do you use?
iostream.h is long deprecated -- use #include <iostream> (no .h) instead.
If that doesn't compile for you, then you really need to get a better compiler.

Also, you would normally have to #include <ctime> to use the time function.
(Just saying)
Topic archived. No new replies allowed.