"Guess the number" game...

I'm trying to make the "Guess the number" game. I started learning C++ today. Here's the code i wrote so far:

#include <iostream>
#include <string>
using namespace std;

int main()
{
int x, y;
y = rand() % 10;
x = 0;

cout << "Hello!" << endl;
cout << "What is your name?" << endl;
string myName;
cin >> myName;
cout << "Well, " << myName << ", I'm thinking of a number between 1 and 10." << endl;
cout << "Take a guess!" << endl;
cin >> x;

while (x != y)
{
if (x < y)
{
cout << "Your guess is too low." << endl;
cout << "Take a guess!" << endl;
cin >> x;
}
else if (x > y)
{
cout << "Your guess is too high." << endl;
cout << "Take a guess!" << endl;
cin >> x;
}
else if (x == y)
cout << "Congratulations." << endl;
}

system("pause");
return 0;
}


Now i have 2 problems. The first one is the problem with the random number, cuz it always gives me the number 1, and the second one is when i guess the number, it doesn't give me a "congratulations" message. it just says "press any key to continue..."
Please help me...
As to your last problem, not printing "Congratulations": the way you have constructed your loop, "while (x !=y)", means that the "else if (x == y)" will never be reached. Just put the printing of "Congratulations" outside the while loop.
Thanks man. That solved it. Can you help me about my first problem?
Call srand ( time ( 0 ) ); at the beginning of the program.
srand seeds rand giving it a bit more randomness
You need to seed the RNG with srand(time(0));
Thanks a lot guys. :D
Plus, rand() % 10 wil give you a number from 0 to 9.
rand() % 11 will return 0-10 and rand() % 10 + 1 will give 1-10. Also, when you ask a number 'between 1 and 10' the user will probably understand 2-9.
Last edited on
Topic archived. No new replies allowed.