Generate a random unicode string

不问归期 提交于 2021-02-08 09:24:06

问题


In VS2010, this function below prints "stdout in error state", I'm unable to understand why. Any thoughts on what I'm doing wrong?

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'\0';

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

回答1:


Thanks to @0x499602D2, I found out I had an array out of bounds error in my functions. To be more clear, I wanted my function to construct an unicode string whose characters are in the range [start, end]. This was my final version:

// 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 '\0'
    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'\0'; 
    return ustr;
}

When this function is called as follows, it generates an unicode string with 5 cyrillic characters.

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: This function as weird and arbitrary as it may seem, serves a usual purpose for me, I need to generate sample strings for a unit-test case that checks to see if unicode strings are written and retrieved properly from a database, which is the backend of a c++ application. In the past we have seen failures with unicode strings that contain non-ASCII characters, we tracked that bug down and fixed it and this random unicode string logic serves to test that fix.



来源:https://stackoverflow.com/questions/23853489/generate-a-random-unicode-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!