< Previous | Contents | Next >
My next task is to pick a word to jumble—the word the player will try to guess. First, I create a list of words and hints:
int main()
{
enum fields {WORD, HINT, NUM_FIELDS}; const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Do you feel you’re banging your head against something?"},
{"glasses", "These might help you see the answer."},
{"labored", "Going slowly, is it?"},
{"persistent", "Keep at it."},
{"jumble", "It’s what the game is all about."}
};
108 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble
I declare and initialize a two-dimensional array with words and corresponding hints. The enumeration defines enumerators for accessing the array. For example, WORDS[x][WORD] is always a string object that is one of the words, while WORDS[x][HINT] is the corresponding hint.
Tric k
You can list a final enumerator in an enumeration as a convenient way to store the number of elements. Here’s an example:
enum difficulty {EASY, MEDIUM, HARD, NUM_DIFF_LEVELS};
cout << "There are " << NUM_DIFF_LEVELS << " difficulty levels.";
In the previous code, NUM_DIFF_LEVELS is 3, the exact number of difficulty levels in the enumeration. As a result, the second line of code displays the message, "There are 3 difficulty levels."
Next, I pick a random word from my choices.
srand(static_cast<unsigned int>(time(0))); int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][WORD]; // word to guess string theHint = WORDS[choice][HINT]; // hint for word
I generate a random index based on the number of words in the array. Then I assign both the random word at that index and it’s corresponding hint to the variables theWord and theHint.