Reputation: 370
Im looking for help with my code. Im doing app, that will be downloading random images from Imgur.com, and I've stuck on their names generator.
This is the code, that I have
char letter;
unsigned short int asciiCode = 0;
std::string imageName = "";
std::ofstream fileToStoreImageNames;
if (!fileToStoreImageNames.is_open())
return -1;
for (auto i = 0; i < 6; i++)
{
/* if getTrueOrFalse()==0 return capitalLetter() if not return smallLetter() */
asciiCode = random.getTrueOrFalse() == 0 ? random.upperCase() : random.lowerCase();
letter = static_cast <char>(asciiCode);
if (imageName.size() > 0)
imageName += letter;
else
imageName = letter;
}
fileToStoreImageNames << imageName << std::endl;
I made some generators, that are returning numbers from defined range(in case of random.upperCase() it is range of 65 to 90), there is 50% chance for upperCase and 50% for lowerCase. Later im converting those numbers by static_cast to char. For now Im only writing those names to file, and I can see it isnt working as intended. If i just compile this code, It is writing to file something like
bbbbbb
rrrrrr
YYYYYY
vvvvvv
UUUUUU
EEEEEE
rrrrrr
but, when I debug it step by step, it is working as it should be and I get random letters. There is my file after 11 attempts, lines 8 and 11, are result of step by step debugging.
Upvotes: 0
Views: 198
Reputation: 769
Instead of seeding your RNGs on every call to the random
functions, do it once in the constructor of that class, then store and reuse the generator all over the class member functions. Your problem occurs because if they get seeded with the same timestamp they produce the same results, thus you get the same characters calling the function multiple times within the same second. When using C++11 random library you shouldn't even use a timestamp as seed.
Upvotes: 1
Reputation: 880
Your program seems to be too fast. If you debug your code time passes and you Random Number Generator (RNG) gets a different time point from your OS. RNGs use the current time to deliver pseudo random numbers.
You can use RNGs from the c++11 standard pseudo random number generation. The RNG object is instanciated once and will provide a different random number in every cycle of the loop.
Upvotes: 1