How to generate random numbers in C++?

Hi, I'm looking for a way to generate random numbers and no idea how, I've tried looking around the web but no examples seem to compile for me, it's likely to do with not having the correct libraries which no archives seem to mention. Lots of posts mention the "time" function but I've never heard of it before and it doesn't compile when I use it.

Any info on syntax to use and which libraries to include would be much appreciated. :)
Last edited on
http://www.cplusplus.com/reference/cstdlib/rand/

1
2
3
4
5
6
7
8
#include <cstdlib>
#include <iostream>

int main()
{
    std::cout << std::rand();
    return 0;
}
1
2
3
4
5
6
#include <ctime>
//...
srand((int)time(0));
// random number from 1-10
x = rand() % 10 + 1; 
//... 
Last edited on
But don't forget to call srand() once, near the beginning of main, to seed the random number generator. Bourgond Aries's example gives me 41 every time I run it.

See the the reference entry of rand for a more complete example.

Andy
Thanks for the replies guys, problem solved :)
Topic archived. No new replies allowed.