[英]Reading And Writing Windows Registry in C++ (How to convert string to wchar(?))
This is a part of my assignment.这是我任务的一部分。 I know how to open/read registry keys and create values, but i have few questions.
我知道如何打开/读取注册表项并创建值,但我有几个问题。 My code:
我的代码:
This is how i write new string value into registry:这就是我将新字符串值写入注册表的方式:
void lCreateKeyOne(HKEY hKey, LPCWSTR lSubKey)
{
WCHAR wcValue[] = TEXT"testvalue";
LONG lNewValue = RegSetValueEx (hKey,
L"MytoolsTestKey",
NULL,
REG_SZ,
(LPBYTE)wcValue,
sizeof(wcValue));
}
It works, but i want to generate random string and write it into registry key.它有效,但我想生成随机字符串并将其写入注册表项。 This is how i generate random string:
这就是我生成随机字符串的方式:
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
srand(time(0));
string Str;
for (unsigned int i = 0; i < 20; ++i)
{
Str += genRandom();
}
static wchar_t const * const alphanum{
L"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz" };
constexpr auto stringLength{ wcslen(alphanum) };
wchar_t genRandom()
{
return alphanum[std::rand() % stringLength];
}
// ...
std::srand(static_cast<unsigned>(std::time(nullptr)));
std::wstring Str;
for (std::size_t i{}; i < 20; ++i){
Str += genRandom();
}
And what about NOT to use string or std::wstring,不使用字符串或 std::wstring 怎么样,
static wchar_t const * const alphanum{
L"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz" };
constexpr auto stringLength{ wcslen(alphanum) };
wchar_t genRandom()
{
return alphanum[std::rand() % stringLength];
}
// ...
std::srand(static_cast<unsigned>(std::time(nullptr)));
wchar_t Str[20+1] = { 0 };
for (int i = 0; i < 20; i++)
{
Str[i] = genRandom();
}
I tried to use char instead of wchar and it writes chinese characters
我尝试使用 char 而不是 wchar 并且它写中文字符
Because your method RegSetValueEx
is reference to RegSetValueExW
which received as wide character format.因为您的方法
RegSetValueEx
引用了以宽字符格式接收的RegSetValueExW
。 sizeof(char) = 1
and sizeof(wchar_t) = 2
, The value of two char
characters is read as a wchar_t
character(which as you see in chinese characters). sizeof(char) = 1
和sizeof(wchar_t) = 2
,两个char
字符的值被读取为一个wchar_t
字符(如你所见的中文字符)。 You can specifically reference to RegSetValueExA
if you want to try using char
.如果您想尝试使用
char
您可以专门参考RegSetValueExA
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.