C++ Random Code Generator

Echo89 0 Tallied Votes 7K Views Share

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

#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;
}
vijayan121 1,152 Posting Virtuoso

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 ;
}
Echo89 9 Web Developer

Thanks a lot!

5n0wn1nja 0 Newbie Poster

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.