I am trying to use the rand() and srand() function to generate a random number in the index of an array, but it outputs the same thing every single time. What gives? I want my output to be able to display a different color every time I execute my code.
AREAS OF FOCUS:
void randomPick()
int random = rand() % 7; cout << "Random color = " << colors[random] << endl;
srand((unsigned int)time(NULL))
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class randColor
{
private:
string colors[7];
public:
// set element to assign values to array
void setElement(int index, string color)
{
colors[index] = color;
}
void printColor()
{
int i = 0;
for(i = 0; i < 7; i++)
{
cout << colors[i] << endl;
}
}
void randomPick()
{
int random = rand() % 7;
cout << "Random color = " << colors[random] << endl;
}
};
int main()
{
srand((unsigned int)time(NULL));
randColor RandomOne;
const string colors[7] = {"red", "orange", "yellow", "blue", "green", "indigo", "violet"};
for (int i = 0; i < 7; i++)
{
RandomOne.setElement(i, colors[i]);
}
RandomOne.printColor();
RandomOne.randomPick();
return 0;
}