每次在C ++中生成相同的随机字符

时间:2014-03-27 05:19:21

标签: c++

您好我正在尝试编写代码以返回随机字符,因此我编写以下代码:

static char prepare-data()
{
    Sleep(rand()%500); // sleep random amount
    int n = rand()%26;
    char c = (char)(n+65);
    return c; // return random character
}

static void writer()
{
    int i, writePt = 0;
    char data;
    for (i = 0; i < data_length; i++)
    {
        data = preparedata(); // go off & get data ready
        buffers[writePt] = data; // put data into buffer
        cout<<"writer thread: buffer["<<writePt<<"]="<<data<<endl;
        writePt = (writePt + 1) % num_total_buffer;
    }
}

但每次我运行代码我都会得到相同的字符 这被视为问题

1 个答案:

答案 0 :(得分:4)

也许你想添加

/* initialize random seed: */
  srand (time(NULL));

在使用rand()之前