Randomizing words in Hangman

Ok so I'm having difficulty creating my hangman game. I've started with some code and I'm currently stuck at randomizing my mystery words. This hangman selects 5 words from a file of 4965 words and puts them into a struct. I have no clue how to get them to randomize. I have numbers chosen to select the words from the file... but i can't get those words from the file.

I hope that makes sense...

Here's the code I have so far.

//words.txt contains 4965 words
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>

using namespace std;

const int maxWrongGuesses = 8;

struct gameWordStruct{
string word;
string guessedRight;
};

void selectWords( int words[5] )
{
int tmp;

// get some random numbers
srand((unsigned)time(0));
words[0] = rand() % 4965;
words[1] = rand() % 4965;
words[2] = rand() % 4965;
words[3] = rand() % 4965;
words[4] = rand() % 4965;

// sort them so the smallest comes first
for( int i = 0; i < 5; i++ )
for( int j = 0; j < 4; j++ )
{
if( words[j] > words [j+1] )
{
tmp = words[j];
words[j] = words[j+1];
words[j+1] = tmp;
}
}
}

int main()
{
int randomWordIndexes[5];
selectWords( randomWordIndexes );

gameWordStruct gameWords[5]; // an array of structs that holds the mystery words
string incorrectGuesses;
char letter;

// read the words from the file
fstream fin;

fin.open("words.txt");


fin >> gameWords[0].word;
cout << gameWords[0].word << endl;
fin >> gameWords[1].word;
cout << gameWords[1].word << endl;
fin >> gameWords[2].word;
cout << gameWords[2].word << endl;
fin >> gameWords[3].word;
cout << gameWords[3].word << endl;
fin >> gameWords[4].word;
cout << gameWords[4].word << endl;




// now we have the words

// loop

// Ask for a letter


// see if the letter is in one of the words
// if not, update our miss count
// if it is, then add the letter to the underscore string


// see if we finished a word
// if so, then quit


// end loop

system("pause");

return 0;
}


I just need a little guidance to get me back on the right track...

EDIT: I know the seekg function but that finds the specific byte according to that random number... I need the entire word.

random number may be 2116 and i need the 2116th word
Last edited on
Well, what you could do is read the entire file into an array and then get the correct word from the array (using getline()). (Although this might not be the fastest or efficient way)
Topic archived. No new replies allowed.