在 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/