终端为什么跳过我的while语句?

问题描述 投票:0回答:2

这是我为使用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";
  }

}
c++ loops while-loop logic
2个回答
0
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.