My pickRandomWord() function

I decided to look for a dictionary of common words and then use the code from the course to pluck out just the 3 to 7 letter isograms from that dictionary. The best dictionary I could find had just 1,000 words in it which I feel is perfect for the game. After discarding the inappropriate words, I was left with 650 words which I loaded into a text file called isograms.txt which you can find here

What follows is the function I wrote to pick out a random word from the 650 word list. (Sorry about the incorrect formatting, it wasn’t clear to me how to post code in this forum.)

First, at the top, 2 additional includes, one for the random seed based on time and the other for file handling…

#include “time.h” // had to use quotes instead of chevrons because with chevrons it wouldn’t compile
#include “fstream.h” /* used chevrons instead of quotes here but it wouldn’t show up in this post, so I switched to quotes */

…and now the function…

FString FBullCowGame::pickRandomWord()
{
constexpr int32 NUM_WORDS_IN_FILE = 650;
FString WordList[NUM_WORDS_IN_FILE];
FString CommonWord;

    // open the text file of isograms, which is a file of 650 words, one word per line.
std::ifstream myfile("Isograms.txt");
   
   // make sure the file is open
if (myfile.is_open())
{
	int Count = 0;


	while (getline(myfile, CommonWord))
	{
		WordList[Count] = CommonWord;
		Count++;
	}
	myfile.close();
}
// get a seed for the random number generator
srand(time(NULL));

// get a random number between 1 and NUM_WORDS_IN_FILE
int32 randomNumber = rand() % NUM_WORDS_IN_FILE + 1;

return WordList[randomNumber];

}

Privacy & Terms