Archived

This topic is now archived and is closed to further replies.

Ekim_Gram

Random Word Generator?

Recommended Posts

I thought you meant something like a program to generate random names for planets or something.

You need a word list of some kind. I''ve seen a gnu project with a huge wordlist, relating to anagrams. I can''t remember the name. . . ana something I think. I''ll see if I can''t find it.

Share this post


Link to post
Share on other sites
<< Ok, so now I have the list. How do I include it in my C++ program? >>

Two ways I can think of, either inside your code as an array of strings or chars.....

Or...outside your code as a plain text file where you pick one string from the list before the game starts. This way the entire list does not have to saved in an array, you just read until you hit the string you want -- for example, let''s say you have 2000 strings in a text file a line per string, pick a random number like 1575, and read the list until you hit line 1575 and use that string that the person has to guess.

Phil P

Share this post


Link to post
Share on other sites
<< Or better yet, can somebody demonstrate it for me? >>

Naw, to quote someone in the Adam Sandler movies, "you cahn doooo it!!!"

If I was writing a Hangman, I would type in Google "Hangman games" or "Hangman code" or "reading from a file C++" and see how other folks do their word list. You want to find the simplest way of (1) opening a text file for read, (2) reading a line at a time, (3) closing the text file.

Phil P

Share this post


Link to post
Share on other sites
For selecting words just do something simple like so:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <ctime>
#include <cstdlib>

int main()
{
std::ifstream in_file("words.txt");
if ( in_file.fail() )
{
// handle error

}

std::vector<std::string> v_words;
std::copy( std::istream_iterator<std::string>(in_file),
std::istream_iterator<std::string>(), std::back_inserter(v_words) );

srand( unsigned ( time(0) ) ); // seed rand()

std::string word = v_words[ rand() % v_words.size() ];

// now ''word'' is a word randomly selected from your word list


...

// rest of program


...

return 0;
}

You will have to learn some STL stuff; fstream and std::vector in particular.

pkelly83: People have to start somewhere. Drop the arrogance.

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

Share this post


Link to post
Share on other sites