Using Srand

Hello guys, i need some help using srand, the reference page is not very clear how to work it out specifically as how i want to, specifically, i just want to generate a random number between 6 and 10, any help or to guide me to another topic where i can get some help on this, thanks in advance.
1. The srand merely initializes the generator to specific state. It is called only once in the program.

2. The rand() returns a random number. Its documentation has IMHO good explanation: http://www.cplusplus.com/reference/cstdlib/rand/

3. The rand & srand are deprecated. You should learn http://www.cplusplus.com/reference/random/
1
2
3
4
5
6
7
8
9
10
11
12
13
int random(int low, int high)
{
    return std::rand() % (high - low + 1) + low;
}

int main()
{
    /* setting up RND */
    std::srand(std::time(nullptr));
    
    /* using out function */
   int x = random(6, 10);
}


However you should consider getting rid of bad C library randomizer and use C++ ones:

1
2
3
4
5
6
7
8
#include <random>
int main()
{
    std::mt19937 rng(std::time(nullptr));
    std::uniform_int_distribution<> dis(1, 6);

    int i = dis(rng);
}
Thank you very much for your input, however, i did try using the C++ one immediately, but, every time im including , #include <random> im getting an error

" /** @file bits/c++0x_warning.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{iosfwd}
*/

#ifndef _CXX0X_WARNING_H
#define _CXX0X_WARNING_H 1

#ifndef __GXX_EXPERIMENTAL_CXX0X__
#error This file requires compiler and library support for the \
ISO C++ 2011 standard. This support is currently experimental, and must be \
enabled with the -std=c++11 or -std=gnu++11 compiler options.
#endif

#endif "

and im using CodeBlocks latest version, with MinGW compiler, so thats a different problem i assume .. :(
You have not enabled C++11 mode.
Settings → Compiler... → check Have g++ follow the C++11 ISO C++ language standard
Last edited on
oh man ... Thanks very much for your time :)
Topic archived. No new replies allowed.