Random command

How do I make a "random" command, I want to make a program that says a random colour, please help.(This is not a homework assignment, just for fun)
You could use a std::vector and map a value to each index.

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
#include <iostream>
#include <vector>
#include <ctime>
#include <string>

int main( int argc, char* argv[] )
{
   std::vector<std::string> colours;

   // Set up some colours. You could do this in a function somewhere.
   colours.push_back( "Red" );
   colours.push_back( "Green" );
   colours.push_back( "Blue" );

   // Seed PRNG
   srand( time( NULL ) );

   // Get a random number between 0 and 2 inclusive
   int idx = rand()%3;

   // Print
   std::cout << "A random colour is " << colours[idx] << std::endl;

   return 0;
}
Thanks for the fast reply
Do you have to put std:: each time?
You can put using std namespace; at the top then you don't have to. I generally like to avoid doing it but it should be fine on a small project like this.

On the other hand, you could do something like this:
1
2
3
4
using std::vector;
using std::string;
using std::cout;
using std::endl;
you could also use a color-space (like rgb or hsv or ...) and then the srand,rand functions with the modulo operator on the maximum values of each colorspace.

so for RGB:
r=rand()%255;
g=rand()%255;
b=rand()%255;

this way you have a random color of the whole color space and not just a color of a predefined choice.



regarding the "std::". you should use it like this.
using namespace std would also work and won't get you into trouble here
Thanks for all the help
Topic archived. No new replies allowed.