-3

My code:

#include <iostream>
#include <random>

void main()
{
  std::random_device rd;

  std::cout << "Random value: " << rd() << std::endl;

  system("pause");
}

How do i get the result rd(), and convert it to std::string?

Martin G
  • 17,357
  • 9
  • 82
  • 98

4 Answers4

4

Since you are asking how to convert the result of std::random_device to a string, and std::random_device returns an unsigned int. C++11 provides std::to_string, can be used to convert numbers to strings. See here.

#include <iostream>
#include <random>
#include <string>

int main()
{

    std::random_device rd;
    std::string str = std::to_string(rd());
    std::cout << str << std::endl;

    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

Here's an example I found on http://en.academic.ru/dic.nsf/enwiki/11574016

#include <random>
#include <functional>

std::uniform_int_distribution<int> distribution(0, 99);
std::mt19937 engine; // Mersenne twister MT19937
auto generator = std::bind(distribution, engine);
int random = generator();  // Generate a uniform integral variate between 0 and 99.
int random2 = distribution(engine); // Generate another sample directly using the       distribution and the engine objects.

I haven't worked with it before, but this might help you get started.

Nathan
  • 73,987
  • 14
  • 40
  • 69
1

std::stringstream is one way to convert a number to a string, the code below shows various engines and distributions possible. It defaults to Mersenne Twister for the engine and the normal distribution. This is good reference for the options available:

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <sstream>

int main()
{
    std::random_device rd;

    //
    // Engines 
    //
    std::mt19937 e2(rd());
    //std::knuth_b e2(rd());
    //std::default_random_engine e2(rd()) ;

    //
    // Distribtuions
    //
    std::normal_distribution<> dist(2, 2);
    //std::student_t_distribution<> dist(5);
    //std::poisson_distribution<> dist(2);
    //std::extreme_value_distribution<> dist(0,2);

    std::stringstream s1 ;

    s1 << dist(e2) ; 

    std::string str1 = s1.str();

    std::cout << str1 << std::endl ;
}

another method to convert to a string would be to use std::to_string:

 str1 = std::to_string( dist(e2) ) ;
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0
#include <stdlib.h>
#include <time.h>

int main(){
    srand(time(NULL));
    unsigned int maxValue = 50;
    std::cout << "Random value: " << rand()%maxValue; //random between 0-50

    return 0;
}
Kevin
  • 2,739
  • 33
  • 57