3.7.2 选择单词
接下来的任务是选择一个单词来打乱顺序,玩家将要猜的就是这个单词。首先,程序创建了一个单词列表以及提示:
- 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."}
- };
程序用单词和相应的提示声明并初始化了一个二维数组。枚举类型定义了用于访问数组的枚举数。例如,WORDS[x][WORD]总是表示单词的string对象,而WORDS[x][HINT]则是相应的提示。
技巧
还可以很方便地在枚举类型中最后添加一个枚举数,用来存储元素的个数,如下例所示:
- enum difficulty {EASY, MEDIUM, HARD, NUM_DIFF_LEVELS};
- cout << "There are " << NUM_DIFF_LEVELS << " difficulty levels.";
上面的代码中NUM_DIFF_LEVELS为3,恰好是枚举类型中难度等级的数目。因此,代码第二行显示消息"There are 3 difficulty levels."。
接下来随机地选择一个单词。
- 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
上面的代码基于数组中单词的数目生成了一个随机索引号,然后将该索引处的单词和相应提示赋值给了变量theWord和theHint。