用 switch 开关语句实现猜词游戏。
时间: 2023-07-18 07:30:25 浏览: 174
guesswords_搭档猜词_delphi7_
好的,以下是使用 switch 语句实现猜词游戏的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "apple";
string guess;
int tries = 0;
const int maxTries = 5;
cout << "欢迎来到猜词游戏!" << endl;
while (tries < maxTries) {
cout << "请输入你猜的单词(五个字母):";
cin >> guess;
tries++;
switch (tries) {
case 1:
cout << "第一次猜测:" << guess << endl;
break;
case 2:
cout << "第二次猜测:" << guess << endl;
break;
case 3:
cout << "第三次猜测:" << guess << endl;
break;
case 4:
cout << "第四次猜测:" << guess << endl;
break;
case 5:
cout << "第五次猜测:" << guess << endl;
break;
}
if (guess == word) {
cout << "恭喜你,猜对了!" << endl;
break;
} else {
cout << "猜错了,请再试一次。" << endl;
}
}
if (tries == maxTries) {
cout << "很遗憾,你没有猜对。正确答案是:" << word << endl;
}
return 0;
}
```
以上代码中,我们首先定义了要猜的单词和最多猜的次数。然后在一个循环中,用户每次输入猜测的单词,然后使用 switch 语句根据猜测的次数输出相应的信息。如果猜测的单词与正确答案相同,输出恭喜信息并跳出循环;否则输出猜错信息。如果猜测的次数达到最大次数,输出正确答案。
阅读全文