Friday, 30 June 2017
How do you generate random strings in C++?
Answer
Answer
I am looking for methods to generate random strings in C++.Here is my code:
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
srand(time(NULL));
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
But the seed(time(NULL))
is not random enough.Are there any other better way to generate random strings in C++?
Answer
Don't call srand()
on each function call - only call it once at first function call or program startup. You migh want to have a flag indicating whethersrand()
has already been called.
The sugested method is good except that you misuse srand()
and get predictably bad results.
Subscribe to:
Post Comments (Atom)
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV
In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...
-
Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' ...
-
The whole error output being: LNK2019 unresolved external symbol wWinMain referenced in function "int __cdecl __scrt_common_main_seh(vo...
-
I recently used canvas to conert images to webp, using : const dataUrl = canvas.toDataURL('image/webp'); But this takes a lots of ti...
No comments:
Post a Comment