In: Computer Science
How can I make this not add to the counter when the guess is right?
void guessGenerator(string hangmanStar, string
wordFromWordtxt)
{
char temp = '\0';
bool win = false;
int counter = 0;
while ((win == false) || (counter == 7))
{
char temp;
cout << hangmanStar <<
endl;
cout << "? ";
cin >> temp;
counter++;
for (int i = 0; i <
wordFromWordtxt.length(); i++)
{
if
(wordFromWordtxt.at(i) == temp)
{
hangmanStar.at(i) = temp;
}
}
if (wordFromWordtxt ==
hangmanStar)
{
win =
true;
cout <<
"You win." << endl;
cout <<
"The word was: " << hangmanStar << endl;
}
else if (counter == 7)
{
hangManPicture(counter);
cout <<
endl;
cout <<
"You lost" << endl;
cout <<
"Answer: " << wordFromWordtxt << endl;
return;
}
else
{
if
(hangmanStar.find(temp) == string::npos)
{
cout << endl;
cout << "Oops";
hangManPicture(counter);
cout << endl;
}
else
{
hangManPicture(counter);
cout << endl;
}
}
}
return;
}
Your code seems to increment the counter by 1 for each guess. Now you want that if the guess is right, the counter shouldn't increment. So just use counter--; at the winning condition - This is set the counter back to the previous count. See below code in bold:
void guessGenerator(string hangmanStar, string
wordFromWordtxt)
{
char temp = '\0';
bool win = false;
int counter = 0;
while ((win == false) || (counter == 7))
{
char temp;
cout << hangmanStar <<
endl;
cout << "? ";
cin >> temp;
counter++;
for (int i = 0; i <
wordFromWordtxt.length(); i++)
{
if
(wordFromWordtxt.at(i) == temp)
{
hangmanStar.at(i) = temp;
}
}
if (wordFromWordtxt ==
hangmanStar)
{
win =
true;
cout <<
"You win." << endl;
cout <<
"The word was: " << hangmanStar << endl;
counter--;
}
else if (counter == 7)
{
hangManPicture(counter);
cout <<
endl;
cout <<
"You lost" << endl;
cout <<
"Answer: " << wordFromWordtxt << endl;
return;
}
else
{
if
(hangmanStar.find(temp) == string::npos)
{
cout << endl;
cout << "Oops";
hangManPicture(counter);
cout << endl;
}
else
{
hangManPicture(counter);
cout << endl;
}
}
}
return;
}