无法根据布尔值结束do / while循环 - C ++

时间:2013-10-16 22:20:23

标签: c++ comparison boolean return do-while

固定。谢谢。

在我的下面的代码中,它编译并运行但在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);
}

2 个答案:

答案 0 :(得分:1)

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

this->guess 

而不只是猜测。

答案 1 :(得分: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;
    }
}