#include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
char wordOne[5][9] = { {"elephant"},
{"imperial"},
{"absolute"},
{"absinthe"},
{"computer"} };
char hangman[9] = {"********"};
char guess;
int r;
srand( time(0));
r = rand()%5;
wordOne[r];
cout << "Guess the secret eight letter word before you run out of guesses! Go: " << endl;
for (int x = 0; x < 8; ++x)
cout << hangman[x] << endl;
cin >> guess;
while (hangman[0] == '*' || hangman[1] == '*' || hangman[2] == '*' || hangman[3] == '*' || hangman[4] == '*' || hangman[5] == '*' || hangman[6] == '*' || hangman[7] == '*')
{
cout << "Guess the secret eight letter word before you run out of guesses! Go: ";
for(int x = 0; x < 8; ++x)
cout << hangman[x];
cout << endl;
cin >> guess;
for(int x = 0; x < 8; ++x)
{
if (wordOne[hangman[x]][x] == guess)
{
hangman[x] = guess;
}
}
for(int x = 0; x < 8; ++x)
cout << hangman[x] << endl;
}
system("PAUSE");
return 0;
}
对于一个项目,要求我们创建一个仅显示星号的一维数组。然后,使用二维数组,存储5个不同的8个字母词。该程序应该随机选择一个,然后用户将输入随机字母以猜测单词。它本质上是在复制子手。当猜测字母时,应将星号替换为正确的字母。例如,如果单词是大象,并且首先猜出了e,则程序将显示e ***,依此类推。我已经可以编译该程序了,但是我不知道如何更改代码,以便替换星号并使程序正常运行。任何反馈将不胜感激。
最佳答案
wordOne[hangman[x]][x]
假设x = 1
在代码上等同于wordOne['*'][1]
。不应该是wordOne[r][x] == guess
吗?我添加了一个int
来跟踪猜测的数量,并在while循环中添加了一个检查,以查看用户是否猜测了最大次数。
#include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
char wordOne[5][9] = { {"elephant"},
{"imperial"},
{"absolute"},
{"absinthe"},
{"computer"} };
char hangman[9] = {"********"};
char guess;
int r;
srand( time(0));
r = rand()%5;
wordOne[r];
int numGuesses = 10;
cout << "Guess the secret eight letter word before you run out of guesses! Go: " << endl;
for (int x = 0; x < 8; ++x)
{
cout << hangman[x] << endl;
}
while (numGuesses > 0 && (hangman[0] == '*' || hangman[1] == '*' || hangman[2] == '*' || hangman[3] == '*' || hangman[4] == '*' || hangman[5] == '*' || hangman[6] == '*' || hangman[7] == '*'))
{
cout << "Guess the secret eight letter word before you run out of guesses! Go: ";
for(int x = 0; x < 8; ++x)
{
cout << hangman[x];
}
cout << endl;
cin >> guess;
--numGuesses;
for(int x = 0; x < 8; ++x)
{
if (wordOne[r][x] == guess)
{
hangman[x] = guess;
}
}
for(int x = 0; x < 8; ++x)
{
cout << hangman[x] << endl;
}
}
system("PAUSE");
return 0;
}