I'm new to programming, so I created number guessing game which worked perfectly but I can't seem to finish with the word guessing code. My goal is to print "Congratulations" when the guessed string is correct, but I tried many ways and I still can't make it work.
#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;
}
I'd say most of your problems come down to this line:
while(x!=word[i]);
As the comments suggest, word
is your modified word, not the word list. But also, i
is the wrong index. So save the word index you chose earlier:
size_t wordIndex = rand() % 17;
string word = wordList[wordIndex];
Then change your do
loop condition:
while (x != wordList[wordIndex]);
I'd also recommend that you don't use using namespace std;
.
You could argue about the use of rand()
, but it might not be worth it. Just be aware that rand()
has shortcomings and better alternatives exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.