Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I generate random string using the characters of length(len)? in C

C++
void gen_random(char *s, const int len)
{
    char charset[] = "0123456789!\"#$%&'()*+-/. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}


What I have tried:

I tried doing char randomString
Posted
Updated 6-Sep-19 4:37am
v2
Comments
Patrice T 6-Sep-19 9:26am    
Elaborate!
The question makes no sense.

 
Share this answer
 
Comments
KarstenK 7-Sep-19 15:29pm    
RTFM - the epic answer.

scnr ;-)
Richard has given you the link you need: now all you have to do is use it.
How? Simple: You function gets two parameters, a pointer and a
Use a loop that iterates len times, and inside the loop call the rand function. That returns an integer value, so use the % operator (which returns a remainder) to give you a value between 0 and the length of charset minus one. That is your random index into charset - so fetch the character at the index, and add it to the output and increment the pointer.

You may need to add a null value after the loop if it's to be treated as a string, but that will depend on the defintion of your function. If there aren't enough characters in the memory area passed to your function, don't add it!
 
Share this answer
 
Comments
k5054 6-Sep-19 14:40pm    
Don't forget about srand(). Note that the code given on the MS Docs link does have one issue: because it uses time() to seed rand, it can produce identical results if the program is run more than once within the same second. In general, there's probably a pretty small chance of that happening, but it is something to be aware of, should circumstances require.
Rick York 6-Sep-19 23:47pm    
If that matters you could use timeGetTime() and get milliseconds. The chance of the program starting twice in the same millisecond seems exceedingly remote to me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900