如何在每次执行中生成随机字符串(下一个必须与上一个不同)?

How generate random string (next must be diferent of previous) in each execution?

我有下面的代码,每次执行程序时只生成一个固定的字符串,已经在 2 台计算机上测试过,并且总是生成相同的字符串。那么如何在每次执行时生成不同的字符串呢?

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;
}

// int _tmain(int argc, _TCHAR* argv[])

char str[MAX_PATH]; 
gen_random(str, 10);

rand 通常是一个 Pseudo-Random 数字生成器。数字序列完全由 PRNG 的 seed 确定,如 srand 所设置。由于您没有明确设置种子,因此您总是会得到相同的种子,从而得到相同的序列。

请注意,较新的 <random> header 有更好的解决方案 - 更好的算法、更好的播种、更大的范围、更多的分布,...

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

相同的种子,每次都使用相同的字符串。您需要 srand() 使用随机种子。如果它与安全无关,那么时间通常是一个好种子。否则,您需要从操作系统中获取真正的随机位。在 Linux / Unix 下,你会读到 /dev/random