rand() function: nested if statement

I have a 2 player hangman game for class which outputs to the windows command prompt. I use the random number function to select a word from a file and i want to have player two's word be the same length as player one's. After compiling i have no errors but upon execution only the cursor displays. Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  srand(time(0));
	{
		r = (rand() % 802);
			for(i=0; i<r; i++)
				file >> word1;
	}
	bool length = false;
	while(!length)
	{
		srand(time(0));
		{
			r = (rand() % 802);
				for(i=0; i<r; i++)
					file >> word2;
			if(word2.length() == word1.length())
			length = true;
		}
	}
One way might be to first generate a random word length.
Then load all the words of that length into a vector.
Then select two words at random from that vector?

That way you will know exactly how many words you have before selecting the random number needed to choose one. So you can select a random number that will definitely be lower than or equal to the number of available words of a given length.
edit
Last edited on
Only call srand once at the very start of your program.

By calling it repeatedly you are destroying the random number generation.
Still displays only the cursor, if i comment out the while and if statements it works but the problem is the words are of different lengths. I'll have to try the vector idea or maybe use arrays.
Always use vectors rather than arrays. They are much simpler to create, and much safer to use.
1
2
3
4
5
// create a vector of strings (words)
#include <string>
#include <vector>

std::vector<std::string> word_list;


To read a word from a file and put it in the vector use:

1
2
3
4
5
std::string word;

file >> word;

word_list.push_back(word);


To access your words use this:

1
2
3
4
for(unsigned int i = 0; i < word_list.size(); ++i)
{
    std::cout << "word " << i << " = " << word_list[i] << std::endl;
}

Last edited on
Azimer wrote:
Still displays only the cursor, if i comment out the while and if statements it works but the problem is the words are of different lengths. I'll have to try the vector idea or maybe use arrays.


I think the problem is that by the time you come to select the second word you are already half way through the file. Given that you have no idea how many words of a given length are going to be in the file it makes sense to read all the words of the given length in first. Then when you know how many of them that there are word_list.size(); you can easily select two from the list at random.
Topic archived. No new replies allowed.