生成一个随机的unicode字符串

Generate a random unicode string

本文关键字:随机 unicode 字符串 一个      更新时间:2023-10-16

在VS2010中,下面的函数打印"标准输出错误状态",我无法理解为什么。你知道我做错了什么吗?

void printUnicodeChars()
{
    const auto beg = 0x0030;
    const auto end = 0x0039;
    wchar_t uchars[end-beg+2];
    for (auto i = beg; i <= end; i++) {
        uchars[i-beg] = i; // I tried a static_cast<wchar_t>(i), still errors!
    }
    uchars[end+1] = L'';
    std::wcout << uchars << std::endl;
    if (!std::wcout) {
        std::cerr << std::endl << "stdout in error state" << std::endl;
    } else {
        std::cerr << std::endl << "stdout is good" << std::endl;
    }
}

多亏了@0x499602D2,我发现我的函数中有一个数组越界错误。为了更清楚,我希望我的函数构造一个unicode字符串,其字符在[start, end]范围内。这是我的最终版本:

// Generate an unicode string of length 'len' whose characters are in range [start, end]
wchar_t* generateRandomUnicodeString(size_t len, size_t start, size_t end)
{
    wchar_t* ustr = new wchar_t[len+1];      // +1 for ''
    size_t intervalLength = end - start + 1; // +1 for inclusive range
    srand(time(NULL));
    for (auto i = 0; i < len; i++) {
        ustr[i] = (rand() % intervalLength) + start;
    }
    ustr[len] = L''; 
    return ustr;
}

如下所示调用此函数时,它生成一个包含5个西里尔字符的unicode字符串。

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    wchar_t* output = generateRandomUnicodeString(5, 0x0400, 0x04FF);
    wcout << "Random Unicode String = " << output << endl;
    delete[] output;
    return 0;
}

PS:这个函数看起来很奇怪和任意,对我来说是一个通常的目的,我需要为一个单元测试用例生成示例字符串,检查unicode字符串是否被正确地从数据库中写入和检索,这是一个c++应用程序的后端。在过去,我们已经看到了包含非ascii字符的unicode字符串的失败,我们跟踪了这个错误并修复了它,这个随机的unicode字符串逻辑用于测试该修复。