I wrote the following code:
#include <iostream>
#include <time.h>
#include <string.h>
int main()
{
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
std::string word;
unsigned long long int i = 0;
srand(time(NULL));
while(true)
{
int randomIndex = rand() % 27;
word += alphabet[randomIndex];
// If the word might be the desired word, "hi"
if (word.size() == 2)
{
// The word should only be printed if its length is equal to 2
std::cout << i << " : " << word << word.size() << std::endl;
if (word == "hi")
{
break;
}
else // The word isn't "hi". We reset the variable word and continue looping
{
word = "";
}
i += 1;
}
}
return 0;
}
It is supposed to put together random letters until word is equal to "hi". Until that, only 2-character words should be printed, but for some reason the program seems to be thinking that 1-character words have a length of 2. Therefore it also prints 1-character words.
Can anyone please help me?
std::string::sizereturns the number of chars appended, even in one of them is non-printable such as the terminating 0 char.std::stringis for good reason not a C-style string in terms of what its length is defined to be.int randomIndex = rand() % 27;should beint randomIndex = rand() % 26;by using 27 you are going 1 position past thezstored in the string. Thankfully this value is\0