Problem with rand()

I am having a issue with rand(), I only really half way through the tutorial so sorry if this is a obvious issue but was a bit bored so figured I would try to reinforce some of the things I am learning.

The number being generated is always 2 this is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
#include <stdlib.h>

using namespace std;

int main ()
{
    int random = rand() % 10 + 1;
    int guess;
    
    do {
        cout << "Guess the number between 1-10:" << endl;
        cin >> guess;
        if (guess == random)
            cout << "Congratulations! You guessed correct." << endl;
        else
            cout << "Sorry incorrect.\n" << endl;
    } while (guess != random);
    
    system("PAUSE");
}


The odd thing is when I made a test script and used this
1
2
3
4
random = rand() % 10 + 1;
cout << random;
random = rand() % 10 + 1;
cout << random;

and repeated it, it would always generate a different number?


Also just as a side question is there anything wrong with using only endl and not \n I tend to prefer to use endl as it seems cleaner to read but I feel obliged to use \n.
Last edited on
In any application where you plan on using "rand()" always call "srand()" first, but only ever call it once per instance of the application: http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

This function sort of initializes "rand()" (this is not really what it does but it is a simplified way of looking at it).
Last edited on
Seems to be good now I linked it with time like it says.

Cheers for help.
Topic archived. No new replies allowed.