为什么编译器跳过我的while语句?

时间:2019-12-02 02:34:44

标签: c++ loops while-loop logic

这是我为C ++练习而开发的一个简单而愚蠢的循环练习。

这里的问题是当我在终端中手动输入“ h”时,我希望看到在if循环中构造的输出。但是,终端返回 改为while循环。我怀疑是因为我不确定数据类型,但我不确定。

这是我写的:

#include <iostream>
using namespace std;

int main() { 

char letter;
int attempts = 0;
char h;

cout << "Welcome user.\n\n";
cout << "Before we begin,\n";
cout << "might I ask what your favorite letter is?\n";
cout << "For arbitrary reasons only.\n\n";
cin >> letter;




  while (letter !=h && attempts <= 2) {
      cout << "That is a sad letter\n";
      cout << "and not the kind of letter we're looking for here.\n";
      cout << "Please choose another.\n\n";
      cin >> letter;
      attempts++;
  }

  if (letter == h) {
      cout << "Ah, what a wonderful letter.\n";
      cout << "Let us continue on and not worry ourselves with such trivial matters\n";
  }

}

2 个答案:

答案 0 :(得分:0)

您需要在while循环和if语句中的'h'周围加上单引号,或者将'h'分配给变量(char h ='h')。但是,仅执行其中之一,而不同时执行两者,否则它们将互相抵消。 希望这会有所帮助。

答案 1 :(得分:0)

您需要给h赋一个值,此功能才能起作用。例如char h ='h';