Home >Backend Development >C++ >How to Generate a Random Alpha-Numeric String of Specified Length in C ?

How to Generate a Random Alpha-Numeric String of Specified Length in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 12:57:17980browse

How to Generate a Random Alpha-Numeric String of Specified Length in C  ?

Creating a Random Alpha-Numeric String in C

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn