How to "randomize" a sequence of numbers each time a function is called?

I'm trying make a little guessing game with numbers as practice, here is my code I know it's not pretty but I'm making it work, my question is about the random feature, going through this site and others I could make a random sequence of numbers to go into a vector when I start the program but I'm not able to change it every time the game asks to play again and calls the function castDice() again it just prints the same sequence of numbers, I know it has to do something with the seed but I don't understand how to make it work the way I want to, some help would be appreciated.


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
void castDice()

int main()
{
	//seed.
	srand(time(NULL));
	
	 cout << endl;
		
//GAME:
	castDice(); //"random" number
	showIntro(); // text showing instructions
	playGame(); // plays the game
	
	askAgain(); //asks to play again here the function castDice() is called again.
		
	return 0;

}

void castDice()
{
	int randNum;
	randNum = rand() % 10;
	cout << "random num: " << randNum << endl; //DELETE AFTER PLAYING.

	for (int q = 0; q < 4; q++) {
		int randNum = rand() % 10;
		number.push_back(randNum);
		cout << number[q] << ' '; //PRINTS THE SAME SEQUENCE EVERY TIME.
	}
	cout << endl;
}


thanks in advance, if you want me to I can paste the rest of the code.
I don't see where you ever remove any elements from number. All you do is add to it, which means that once you have 4 values in the container and since you always print only the first 4 values, you always print the same values even though there are different numbers in the container.

Try inserting a number.clear(); prior to the for loop that adds values to the container in castDice.
Just piggybacking on this post,

Is there a benefit to using a vector here vs. a standard array? You'd be able to overwrite the positions each time you looped with a standard array. I thought the benefit to a vector was if you needed a dynamic array?

Alternatively why even use push_back or clear? Can't you just call the vector locations as you would an array number[q] = randNum;
Last edited on
Topic archived. No new replies allowed.