Windows CE系统生成随机数字符串

srand函数用于初始化随机数生成器,rand函数用于产生随机数。srand的参数称为随机数种子,要确保rand函数产生真正的随机数(每次生成的随机数不同),随机数种子就要设置为不同的值。(In order to generate random-like numbers, srand is usually initialized to some distinctive value)

通常以系统时间作为随机数种子,最常用的方式是:srand(time(NULL));,但Windows CE编程时,c库不支持time函数,所以这里以GetTickCount代替。另外注意下面函数中的for循环,由于for循环执行速度很快,所以在(unsigned)GetTickCount()之后加上一个i很必要。

CString GetRandomString(int string_length)
{
    CString string_temp, string_result;
    const TCHAR number_array[] = _T("0123456789");

    for (int i = 0; i < string_length; ++i)
    { 
        srand((unsigned)GetTickCount() + i);
        int x = rand()%10;
        string_temp.Format(_T("%c"), number_array[x]); 
        string_result += string_temp; 
    }

    return string_result;
}

 

posted on 2012-12-12 07:51  zhuyf87  阅读(1097)  评论(0)    收藏  举报

导航