The problem I am having is the the output from "printf(nick);" is garbled. I have included the output from the console. The desired character are at the tail end of the above console output. Any help and ideas will be warmly welcomed!!
Simplest fix (not tested) is to zero-initialize the array. char nick [20] { };
But there's still an issue when your string is 20 characters long, because there will be no room for the null char. I would make your array 21 characters long... or just avoid char arrays.
#include <windows.h>
#include <iostream>
#include <string>
#include <random>
char genRandom(const std::string& alphanum)
{
// create a default C++ random engine, seeding it with random_device
static std::default_random_engine rng(std::random_device {} ());
// create a distribution from 0 to the size of the passed string
static std::uniform_int_distribution<int> dis(0, alphanum.size() - 1);
return alphanum[dis(rng)];
}
int main()
{
std::string alphanum =
"0123456789""!@#$%^&*""ABCDEFGHIJKLMNOPQRSTUVWXYZ""abcdefghijklmnopqrstuvwxyz";
std::string Str;
for (unsignedint i = 0; i < 20; ++i)
{
Str += genRandom(alphanum);
std::cout << Str << '\n';
}
std::cout << '\n' << Str << '\n';
Sleep(5000);
}
Why static in the function? So the random engine and distribution objects are not created with each function call. Repeated object creation is resource wasteful.
#include <windows.h>
#include <iostream>
#include <string>
#include <random>
int main()
{
std::string alphanum =
"0123456789""!@#$%^&*""ABCDEFGHIJKLMNOPQRSTUVWXYZ""abcdefghijklmnopqrstuvwxyz";
// create a default C++ random engine, seeding it with random_device
std::default_random_engine rng(std::random_device {} ());
// create a distribution from 0 to the size of the string
std::uniform_int_distribution<int> dis(0, alphanum.size() - 1);
std::string Str;
for (unsignedint i = 0; i < 20; ++i)
{
Str += alphanum[dis(rng)];
std::cout << Str << '\n';
}
std::cout << '\n' << Str << '\n';
Sleep(5000);
}