设为首页 加入收藏

TOP

3.7.2 选择单词
2013-10-07 14:43:43 来源: 作者: 【 】 浏览:60
Tags:3.7.2 选择 单词

3.7.2  选择单词

接下来的任务是选择一个单词来打乱顺序,玩家将要猜的就是这个单词。首先,程序创建了一个单词列表以及提示:

  1. int main()  
  2. {  
  3. enum fields {WORD, HINT, NUM_FIELDS};  
  4. const int NUM_WORDS = 5;  
  5. const string WORDS[NUM_WORDS][NUM_FIELDS] =  
  6. {  
  7. {"wall", "Do you feel you’re banging your head against something "},  
  8. {"glasses", "These might help you see the answer."},  
  9. {"labored", "Going slowly, is it "},  
  10. {"persistent", "Keep at it."},  
  11. {"jumble", "It’s what the game is all about."}  
  12. };  

程序用单词和相应的提示声明并初始化了一个二维数组。枚举类型定义了用于访问数组的枚举数。例如,WORDS[x][WORD]总是表示单词的string对象,而WORDS[x][HINT]则是相应的提示。

技巧

还可以很方便地在枚举类型中最后添加一个枚举数,用来存储元素的个数,如下例所示:

  1. enum difficulty {EASY, MEDIUM, HARD, NUM_DIFF_LEVELS};  
  2. cout << "There are " << NUM_DIFF_LEVELS << " difficulty levels."; 

上面的代码中NUM_DIFF_LEVELS为3,恰好是枚举类型中难度等级的数目。因此,代码第二行显示消息"There are 3 difficulty levels."。

接下来随机地选择一个单词。

  1. srand(static_cast<unsigned int>(time(0)));  
  2. int choice = (rand() % NUM_WORDS);  
  3. string theWord = WORDS[choice][WORD]; // word to guess  
  4. string theHint = WORDS[choice][HINT]; // hint for word  

上面的代码基于数组中单词的数目生成了一个随机索引号,然后将该索引处的单词和相应提示赋值给了变量theWord和theHint。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.7.3 单词乱序 下一篇3.7.4 欢迎界面

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: