Reputation: 29
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();
}
Upvotes: 2
Views: 379
Reputation: 7210
And what about NOT to use string or 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
Because your method RegSetValueEx
is reference to RegSetValueExW
which received as wide character format. 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). You can specifically reference to RegSetValueExA
if you want to try using char
.
Upvotes: 0
Reputation: 13144
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();
}
Upvotes: 2