我是编程的新手,因此我创建了数字猜谜游戏,该游戏运行良好,但是我似乎无法以单词猜测代码结束。我的目标是在猜出的字符串正确时打印“祝贺”,但是我尝试了很多方法,但仍然无法使它工作。
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int i;
const string wordList[17] = { "television",
"computer", "keyboard", "laptop", "mouse", "phone", "headphones",
"screen", "camera", "sound", "science", "programming",
"entertainment",
"graphics", "intelligent", "memory", "remote" };
string word = wordList[rand() % 17];
for(i = 0; i < word.length(); i++)
{
if(word[i] == 'a' || word[i] == 'e' || word[i] == 'i' ||
word[i] == 'o' || word[i] == 'u')
{
word[i] = '_';
}
}
cout << word << endl;
int n=0;
string x;
do
{
n++;
cin >> x;
}
while(x!=word[i]);
cout<<"Congratulations! You guessed the word!";
return 0;
}
答案 0 :(得分:1)
我想说您的大多数问题都归结为这一行:
while(x!=word[i]);
正如评论所建议的,word
是您修改的单词,而不是单词列表。而且,i
是错误的索引。因此,保存您先前选择的单词索引:
size_t wordIndex = rand() % 17;
string word = wordList[wordIndex];
然后更改您的do
循环条件:
while (x != wordList[wordIndex]);
我还建议您don't use using namespace std;
。
您可以argue about the use of rand()
,但可能不值得。请注意,rand()
有缺点,并且存在更好的选择。