Help! srand (time(0)); not working-- Random color picker

I have to write a program that selects a random color from an array. I used the srand (time(0)); statement but it still gives me the same color each time. Does anyone know why? Here is my code.

// Color.cpp
#include <ctime>
#include <iostream>
using namespace std;
#include <string>
#include <cstdlib>
#include "Color.h"

Color::Color() {
colors[0] = "Red"; colors[1] = "Orange"; colors[2] = "Yellow";
colors[3] = "Green"; colors[4] = "Blue"; colors[5] = "Indigo"; colors[6] = "Violet";
}

string Color::getColor(){
srand (time(0));
int colorPicked = rand () % 7;
return colors[colorPicked];
}
void Color::printArray() {
for (int i = 0; i < 7; i++)
{
cout << colors[i] << endl;
}
}
-----------------------------
#include <ctime>
#include <iostream>
#include "Color.h"
using namespace std;

#include <string>


int main() {

Color C;

cout << C.getColor() << endl << endl;

C.printArray();

return 0;

}

You should only call "srand (time(0))" once in a program.
I'm sorry. I'm still a little bit confused. Where did I call "srand (time(0))" more than once?
Do you mean that you get the same colour if you run the program multiple times within the same second? That's because time(0) returns the time in seconds so on the same second you will use the same seed which means you get the same sequence of random numbers from rand(). Programs are usually not run that often so it's usually not a problem.
In your getColor function. srand(time(0)) will be called every time you call that function. Move it to your constructor and it works fine.

edit: That didn't work either. Call it at the top of main(). That's the only way I know to be sure.
Last edited on
getColor is only called once in the program so it still doesn't explain why he always get the same number.
I didn't get the same number when I used his code though. I did if I called getColor more than once, but not if I ran the program more than once.
I used the srand (time(0)); statement but it still gives me the same color each time. Does anyone know why?

In the code you've presented, srand is called a single time so there are not multiple random numbers to compare against. If you invoke the program multiple times, you should receive differing results.

If main looked like this, on the other hand,

1
2
3
4
5
6
int main()
{
    Color C ;
    for ( unsigned i=0; i<7; ++i )
        std::cout << C.getColor() << '\n' ;
}


I would expect it to print out the same number 7 times as srand is called several times in a row (via getColor) with the same value returned from time.
Topic archived. No new replies allowed.