【问题标题】:Having trouble ending a do/while loop depending on a boolean - C++无法根据布尔值结束 do/while 循环 - C++
【发布时间】:2013-10-25 05:59:15
【问题描述】:

已修复。谢谢。

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

【问题讨论】:

  • 你不能总是假设你运行的系统使用 ASCII。即使你这样做了,'a' 也比 97 清晰得多。请记住,还有一个 islower 函数。
  • 我认为您显示的代码本身不是问题,但它也不完整。我认为还有另一个外循环,你被困在这个外循环中。请添加其余代码(如果不是太多)。
  • 你的代码不能编译(guess 没有在validGuess() 中声明),你是怎么让它运行的???
  • 我认为你是对的丹尼尔;它可能会卡在调用该函数的构造函数中。让我仔细看看;谢谢。编辑:仔细观察;这就是问题所在,我的构造函数被困在一个调用它的循环中。

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


【解决方案1】:

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

this->guess 

而不仅仅是猜测。

【讨论】:

  • 它看起来像一个全局变量,因为它也没有在inputGuess()中定义。
  • @Daniel:我猜是类成员,但是我同意它的范围大于任何一个函数,这个“答案”可能是一种风格上的改进,但不会解决问题。
  • 是的,我明白了。仍然。他“应该”通过它。我们需要查看类的其余部分,可能是实例问题,比如函数是静态的等。如果是类 var,请尝试添加范围解析
  • guess 被私有声明为 hangman 类的一部分;所以不需要通过。猜测是一个空白向量,也是作为 hangman 类的一部分私下声明的。
  • 试试这个->猜 c# 处理得很好,但 c++ 可能需要它
【解决方案2】:

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多