atkinscc
atkinscc

Reputation: 1

Having trouble ending a do/while loop depending on a boolean - C++

Fixed. Thank You.

In my code below, it compiles and runs but gets stuck in the do/while loop. The return values are working but the while loop must not recognize it and it goes indefinitely. I can receive returns of true and false; both do not stop the loop. Really lost here and cannot find an answer. Thank you.

//helper function for inputGuess
//checks if the user's guess is in the lowercase alphabet and that
//  it has not been guessed before
bool Hangman::validGuess() {
  //checks if the character guess is in the lowercase alphabet
  if (guess >= 97 && guess <= 122) {
    //checks if the user's guess has been guessed previously
    if (guessed.size() > 0) {
      for (int i = 0; i < guessed.size(); i++) {
        cout << "enter for\n";
        cout << "guess[i]: " << guessed[i] << endl;
        if (guess != guessed[i]) {
          cout << "1st true: guess has not been guessed\n";
          return true;
        }
        else {
          cout << "1st false: same letter\n";
          return false;
        }
      }
    }
    else {
      cout << "2nd true: guessed size is 0\n";
      return true;
    }
  }
  else {
    cout << "2nd false: not alphabet\n";
    return false;
  }
}

//gets input for guess, checks if guess is valid, adds guess to guessed
void Hangman::inputGuess() {
  bool valid = false;
  do {
    cout << "Please enter your guess: ";
    cin >> guess;
    cout << endl;
    valid = validGuess();
    cout << "valid: " << valid << endl;
  } while (valid == false);
  guessed.push_back(guess);
}

Upvotes: 0

Views: 175

Answers (2)

Chris Olsen
Chris Olsen

Reputation: 3511

You have an undefined return case when guessed is empty, as it falls through and there is no default return.

Regardless, this code seems overly complex. Something like this might be better:

bool HangMan::validGuess() {
    //checks if the character guess is in the lowercase alphabet
    if (isalpha(guess)) {
        //checks if the user's guess has been guessed previously
        if (find(guessed.begin(), guessed.end(), guess) != guessed.end()) {
            cout << "1st false: same letter\n";
            return false;
        }
        else {
            cout << "1st true: guess has not been guessed\n";
            return true;
        }
    } else {
        cout << "2nd false: not alphabet\n";
        return false;
    }
}

Upvotes: 0

AwokeKnowing
AwokeKnowing

Reputation: 8226

you should pass guess as a parameter to validGuess() that's your problem. try adding

this->guess 

instead of just guess.

Upvotes: 1

Related Questions