Home > Backend Development > C++ > body text

How to Generate Random Alphanumeric Strings in C ?

Barbara Streisand
Release: 2024-11-18 19:15:02
Original
838 people have browsed it

How to Generate Random Alphanumeric Strings in C  ?

Creating Random Alpha-Numeric Strings in C

Problem:

Generate a random string of alpha-numeric characters with a user-specified length in C .

Solution:

Efficiently generate random alphanumeric strings using a lookup table:

#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;
}
Copy after login

Note:

  • rand generates low-quality random numbers, so use a better random number generator for more secure applications.

The above is the detailed content of How to Generate Random Alphanumeric Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template