生成一个随机的unicode字符串
Generate a random unicode string
在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字符串逻辑用于测试该修复。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- C++ - Unicode Newline
- 在c++构造函数中使用随机字符串生成器
- 如何将unicode字符串从C++传递到delphi
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- ascii 和 unicode 在处理级别有什么区别吗?
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 如何使用要传递给 mt19937 的可选随机种子参数设计函数
- 在C++中随机生成 20 个非重复数字
- 生成一个随机的unicode字符串