Rand() issue

Hellloooo,

Just working on a real basic random number 'game' if you will.

it goes as follows -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <cstdlib> // cstdlib for rand() function

using namespace std;
using std::string;

int MikeFunction () // Defining function to be called if name is mike

{
	int num1,num2,num3;
	int random = (rand()%10)+1; 

	cout << " Great so your name's mike\n\n Let's play a guessing game.\n\n I'm thinking of a number between 1 and 10\n\n";
	cout << " I will give you 3 attempts to guess this number\n\n";

	cout << " \n Please enter the first number - " ;
		cin >> num1;
	cout << " \n And the next - ";
		cin >> num2;
	cout << " \n And the final number please - ";
		cin >> num3;

	cout << " \n Thanks, i was thinking of " << random << endl;

	if (num1== random)

		cout << "\nCONGRATS... You got it!";

	if (num2== random)

		cout << "\nCONGRATS... You got it!";

	if (num3== random)

		cout << "\nCONGRATS...You got it!";

	else

		cout << "\n Better luck next time!";

	return 0;
}


Right, so this function only gets called if the users name is put in as mike.

It then goes on to ask for 3 numbers from the user between 1 and 10, then compares it to what rand() has generated, and either congratulates the user or says better luck next time depending if the users input matches.

This all compiles fine, the only problem is that each and every time im run this program, it generates the same number...'2'.

I cant think why this would be or how to sort it out...

any advice would be great!
random number generator has to be initialized first
read here:
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

put this line before using rand()
1
2
3
#include <ctime>
//..
srand((unsigned) time(NULL));

Use cin.ignore(); after user input (e.g. cin>>)
Thank you johnkravetzki.

Worked perfectly. I put that line in above the variables and it gives a new number each time now.

Topic archived. No new replies allowed.