本文介绍了如何在C ++中创建一个随机的字母数字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由字母数字字符组成的随机字符串。我想要能够指定字符串的长度。

I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.

我如何在C ++中做这个?

How do I do this in C++?

推荐答案

Mehrdad Afshari的会做的伎俩,但我发现它有点太冗长这个简单的任务。查找表有时会产生奇迹:

Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

void gen_random(char *s, const int len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }

    s[len] = 0;
}

这篇关于如何在C ++中创建一个随机的字母数字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:39