This is a function that generates a string of random characters to the length that you specify.

Edited 4 Years Ago by Echo89

#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>

using namespace std;

string random(int len)
{
	string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	string r;
	srand(time(NULL));
	for(int i = 0; i < len; i++) r.push_back(a.at(size_t(rand() % 62)));
	return r;
}

int main()
{
	cout << random(32) << endl;
	cin.get();
	return 0;
}

srand(time(NULL));

Not a good idea to reseed the linear congruential rng each time the function is called.
Perhaps something like: static int seed_once = ( std::srand( std::time(0) ), 0 ) ; instead.

Or better still, just document that std::rand() is used; and expect main() to call std::srand().

C++11:

#include <string>
#include <random>
#include <ctime>

std::string random_str( std::size_t len )
{
    static const std::string a = 
              "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ;
    static std::mt19937 rng( std::time(0) ) ;
    static std::uniform_int_distribution<std::size_t> distr( 0, a.size() - 1 ) ;

    std::string r ;
    for( std::size_t i = 0 ; i < len; ++i ) r += a[ distr(rng) ] ;
    return r ;
}

Edited 4 Years Ago by vijayan121

vijayan ...ur code seems to freeze my computer everytime i try to open it ...y is this?