srand must be called once and not in each loop.
void setcolor()
{
int col = rand() % 4 + 1;
if (col == 1)
{ cout << "white "; }
else if (col == 2)
{ cout << "brown "; }
else if (col == 3)
{ cout << "black "; }
else if (col == 4)
{ cout << "spotted "; }
}
int main()
{
srand(time(NULL));
for (int i = 0; i <= 5; ++i)
{
setcolor();
}
}
It works this way because srand initialize a "global variable" that is used by rand() function.
time(null) return something like the number of seconds that are elapsed from 1st january 1970. So you are using 5 times the same value because of the initialisation of the "global variable".
However, in C++, it is not the right way to use random values.
Please prefer use random header instead (http://en.cppreference.com/w/cpp/numeric/random) :
#include <iostream>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
std::map<int, int> hist;
std::uniform_int_distribution<int> dist(0, 9);
for (int n = 0; n < 20000; ++n) {
++hist[dist(rd)]; // note: demo only: the performance of many
// implementations of random_device degrades sharply
// once the entropy pool is exhausted. For practical use
// random_device is generally only used to seed
// a PRNG such as mt19937
}
for (auto p : hist) {
std::cout << p.first << " : " << std::string(p.second/100, '*') << '\n';
}
}