i'm trying to make a hangman game with c++ right now and i got a question: how do you get a RANDOM word from a text file?
given there is only a word each line in that file


anyone can help?

Recommended Answers

All 5 Replies

Just a shot in the dark ... Traverse the text find and find out how many lines there are. Then, use a random number generator to generate a random number between 0 and the number of lines and store this as random number X. Then, traverse the text file once again going down X number of lines. Then read that line.

>how do you get a RANDOM word from a text file?
Unless the file is so large that placing it in memory is prohibitive, or you're under stupid restrictions, you read the text file into a suitable data structure that gives you convenient and efficient searching.

Suggestion - create an array of pointers, and as you read in each word, use strdup() to put it on the heap, and save the new pointer in an array somewhere. This way when you get your pseudo-random number, you can just use that as the index of the array lookup (after folding the number down to the array bounds, like csgal said).

As Narue was saying, cleanest way is to load each word from the file into something like a vector<string> myWords, then generate a random number between 0 and the vector's myWords.size(). Then you can simply access the vector via myWords[randomNum]

May be you can use a random word buffer. Store 100 random words to a buffer in one time. After user finishes 100 words (i now no such a person!), read another 100 words.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.