c++ - 生成一个随机的unicode字符串

标签 c++ visual-studio-2010 unicode

在 VS2010 中,下面这个函数打印“stdout in error state”,我不明白为什么。对我做错了什么有什么想法吗?

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

最佳答案

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

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

当按如下方式调用此函数时,它会生成一个包含 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 字符串逻辑用于测试该修复。

关于c++ - 生成一个随机的unicode字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23853489/

相关文章:

c - C中不一致的声明和定义

delphi - 如何操作 UnicodeString 的子字符串而不是子数组?

c++ - 调用condition_variable等待函数时线程如何等待?

c++ - 如何有效地将底层数据从 std::string 移动到另一种类型的变量?

mysql - 使用带有 VS2010 的 vb.net 在 mysql 上插入数据

sql-server - 在 SQL Server 中什么时候必须使用 NVARCHAR/NCHAR 而不是 VARCHAR/CHAR?

delphi - Unicode 中 chr(153)(TM 符号)的等效项是什么

c++ - 在 C++ 中有类似于 typeof 的东西吗?

c++ - 为什么模板试图用 'int&' 而不是 'int' 实例化?

c++ - 如何在 windows/msvs 上的同一个 cmake 项目中构建可执行文件和共享库