Hi guys! Long time listener, first time caller here. I'm doing a hangman program, and I know exactly where I'm stuck - I had to build a function that tested a guess to see if it was alphabetic, or previously used, but try as I might, my getNewGuess(string prevGuesses) function isn't working at all. It looks like I just never go into the loop. If I comment out the function and just use
cin >> guess;
it works fine, and keeps track of prevGuesses.
Here's what I'm working with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
#include <iomanip>
#include <string>
#include "assn.h"
using namespace std;
int main()
{
int wrongGuess = 0;
int guessesLeft = 7 - wrongGuess;
string phrase, prevGuesses;
char guess, validGuess;
cout << "Enter phrase: ";
getline(cin, phrase);
clearScreen();
string unsolved = setupUnsolvedPhrase(phrase);
cout << "Phrase : " << unsolved << endl;
cout << "Enter a guess: ";
cin >> guess;
unsolved = updateUnsolvedPhrase(phrase, unsolved, guess);
cout << endl;
while (phrase!=unsolved)
{
cout << "Phrase : " << unsolved << endl << endl;
cout << "Guessed so far: " << prevGuesses << endl;
cout << "Wrong guesses left: " << guessesLeft << endl << endl;
cout << "Enter a guess: ";
cin >> guess;
//getNewGuess(prevGuesses);
prevGuesses += guess;
cout << "Previous guesses: " << prevGuesses << endl;
unsolved = updateUnsolvedPhrase(phrase, unsolved, guess);
}
cout << "Congratulations!!" << endl;
}
|
My getNewGuess function looks like this, essentially:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
/**
@brief Gets valid guess as input.
A guess is taken as input as a character. It is valid if
1) it is an alphabetic character and
2) the character has not already been guessed
@param prevGuesses the string containing all characters guessed so far
@return a valid guess and only a valid guess as a character
*/
char getNewGuess(string prevGuesses)
{
char guess;
cin >> guess;
prevGuesses += guess;
while (isalpha(guess))
{
for (int i = 0; i< prevGuesses.length(); i++)
{
if (prevGuesses.at(i) != guess)
{
return (guess);
}
else
{
wrongGuess++;
}
}
}
}
|
It's weird because I built two other functions and am using them fine, so I don't see what's going on with this one! I feel like I'm having trouble with the scope of the function, like the instructor talked about in class, but, again, I feel like I'm not returning anything I shouldn't be... Any thoughts? Oh, when I run the program with the function, prevGuesses isn't kept track of properly, and regardless of the next guess I input, it doesn't update my unsolved string, but as soon as I take it out it works properly. I HAVE to have a function that keeps track of prevGuesses and returns guess while isalpha(guess) is true though.
If I'm missing anything, I apologize. I've searched and didn't find anything similar. Any help is greatly appreciated!!