This article addresses the query of how to generate a random string comprising alphanumeric characters of a specified length in C .
The solution presented by Mehrdad Afshari is effective, but for this basic task, it may be somewhat verbose. Lookup tables can provide a more concise approach:
#include <ctime> #include <iostream> #include <unistd.h> std::string gen_random(const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::string tmp_s; tmp_s.reserve(len); for (int i = 0; i < len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return tmp_s; } int main(int argc, char *argv[]) { srand((unsigned)time(NULL) * getpid()); std::cout << gen_random(12) << "\n"; return 0; }
It is important to note that the rand function generates pseudo-random numbers, which may not be of high quality. For more secure applications, consider using a cryptographically strong random number generator (CSPRNG) instead.
The above is the detailed content of How to Generate a Random Alpha-Numeric String of Specified Length in C ?. For more information, please follow other related articles on the PHP Chinese website!