I need to randomly choose one of two options several times in a row. I am using std::rand() function for this, here is the code:
string obfuscate(string str)
{
int i;
int brackets = 0;
unsigned int coinflip;
srand(time(NULL));
for (i = 0; i < str.length(); i++)
{
if (str[i] == '{')
brackets++;
else if (str[i] == '}')
brackets--;
if ((str[i] == ';' || str[i] == '{' || str[i] == '}') && brackets > 0)
{
coinflip = std::rand();
cout << coinflip << endl;
if (coinflip % 2 == 0)
{
string substr = str_gen(brackets);
str.insert(i + 1, substr);
i += substr.size();
}
}
}
return str;
}
The result I get seems very weird. I print every rand() output for debug purposes. Here is what I get However when I debug the program step-by-step, the generated numbers are pretty random. I also tried this cycle in the same project:
int i;
srand(time(NULL));
for (i = 0; i < 20; i++)
{
unsigned int coinflip = rand();
cout << coinflip << endl;
}
The output is pretty decent too. So, my question is, what am I doing wrong in my main cycle, that the numbers are not generated randomly?
Note: I am NOT USING srand() inside a loop, that's not the case here.
Aucun commentaire:
Enregistrer un commentaire