簡體   English   中英

為什么編譯器會跳過我的 while 語句?

[英]Why does the compiler skip my while statement?

這是我為在 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";
  }

}

您需要在 while 循環和 if 語句中的 'h' 周圍加上單引號,或者將 'h' 分配給您的變量(char h = 'h')。 只做其中之一,而不是兩者,否則它們會相互抵消。 希望這可以幫助。

你需要給 h 一個值才能讓它工作。 例如字符 h = 'h';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM