Random Word Generation

Hello! I'm creating a program to input a list of words from a file into an array. From this point, I'm trying to randomly select one of the words stored within the array. To test if the code works, I have told the program to display the random word. Unfortunately, the program does not display anything and acts almost like it's skipping the entire process.

For simplicity, I have commented out the portions of unfinished code.

I am really unsure on what I did wrong exactly and would greatly appreciate if someone can turn me into the right direction.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Constant for the maximum number of words.
const int MAX_NUMS = 100;

int main()
{
	// Variables
	string oneWord, randomWord, words[MAX_NUMS];
	char letter;
	int count = 0, position;

	// Set up random generator
	srand(static_cast<unsigned int>(time(0)));

	// Declare an ifstream object named myFile and open a file.
	ifstream myFile;
	myFile.open("P4Words.txt");

	myFile >> oneWord;
	while (!myFile.eof())
	{
		words[count] = oneWord;
		count++;
		myFile >> oneWord;

	}

	cout << "There are " << count << " words in the file." << endl;

	randomWord = words[rand() % count];
	cout << randomWord; //To test if randomWord works or not.


Try changing line 30 to cout << randomWord << std::endl;
Thank you so much!

My code is working up to this point now!

Just for clarification, does every cout require << endl at the end? I just want to understand exactly why my initial code failed.
The code is fine either way, the difference is that std::endl flushes the text to the console - otherwise the text just stays in the buffer and might not be shown on the screen. If you don't want the newline you can use std::flush.
Ah! I understand now.
Thank you so much for your advice and help!
Topic archived. No new replies allowed.