Home > Backend Development > C++ > How Can I Generate Random Alpha-Numeric Strings in C ?

How Can I Generate Random Alpha-Numeric Strings in C ?

DDD
Release: 2024-11-28 19:39:13
Original
811 people have browsed it

How Can I Generate Random Alpha-Numeric Strings in C  ?

Generating Random Alpha-Numeric Strings in C

Creating random strings consisting of alpha-numeric characters is a common task in programming. In C , there are several approaches to achieve this, each with its advantages and limitations.

One straightforward approach is to make use of look-up tables and the rand() function to generate a random index within the table. Here's an example:

#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

This code demonstrates how random alpha-numeric strings can be generated by simply referencing a look-up table and selecting characters based on random indexes. It is concise and easy to implement.

However, it's important to note that the rand() function generates pseudo-random numbers, which may not be suitable for applications requiring true randomness. For higher quality random number generation, consider using a dedicated library like boost::random.

The above is the detailed content of How Can I Generate Random Alpha-Numeric 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template