I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.
How do I do this in C++?
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.
How do I do this in C++?
I tend to always use the structured C++ ways for this kind of initialization. Notice that fundamentally, it's no different than Altan's solution. To a C++ programmer, it just expresses the intent a tad better and might be easier portable to other data types. In this instance, the C++ function
generate_n
expresses exactly what you want:By the way, read Julienne’s essay on why this calculation of the index is preferred over simpler methods (like taking the modulus).
Here's my adaptation of Ates Goral's answer using C++11. I've added the lambda in here, but the principle is that you could pass it in and thereby control what characters your string contains:
Here is an example of passing in a lambda to the random string function: http://ideone.com/Ya8EKf
Why would you use C++11?
For example:
Sample output.
My 2p solution:
Here's a funny one-liner. Needs ASCII.