0

固定的。谢谢你。

在我下面的代码中,它编译并运行,但卡在 do/while 循环中。返回值正在工作,但 while 循环不能识别它并且它会无限期地运行。我可以收到真假的回报;两者都不会停止循环。真的迷路了,找不到答案。谢谢你。

//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);
}
4

2 回答 2

1

您应该将guess 作为参数传递给validGuess(),这是您的问题。尝试添加

this->guess 

而不是仅仅猜测。

于 2013-10-16T22:26:12.463 回答
0

当为空时,您有一个未定义的返回案例guessed,因为它通过并且没有默认返回。

无论如何,这段代码似乎过于复杂。像这样的东西可能会更好:

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;
    }
}
于 2013-10-16T22:46:13.957 回答