2014-10-07 172 views
-1
int main() 
{ 

int wordCode; 

const int QUIT_MENU = 9; 

菜單爲什麼我的while while循環永遠不會結束? C++

do 
{ 
    cout << "Given the phrase:" << endl; 
    cout << "Now is the time for all good men to come to the aid of their ___.\n" << endl; 
    cout << "Input a 1 if you want the sentence to be finished with party." << endl; 
    cout << "Input any other number for the word country.\n" << endl; 
    cout << "Please input your choice now." << endl; 
    cin >> wordCode; 
    cout << endl; 
    writeProverb(wordCode); 

while (wordCode >= 1 || wordCode <= 2) 
{ 
     cout << "You have not entered a valid selection." << endl; 
     cout << "Please eneter a 1 or a 2." << endl; 

    } 

    if (wordCode != QUIT_MENU) 
    { 
     switch (wordCode) 
     { 
      case 1: 
       writeProverb(wordCode); 
       break; 
      case 2: 
       writeProverb(wordCode); 
     } 
    } 

是退出這個循環的正確方法?

}while (wordCode != QUIT_MENU); 

return 0; 
} 

開始寫諺語的void函數。

void writeProverb (int wordCode) 
{ 
//Fill in the body of the function to accomplish what is described above 

if (wordCode == 1) 
{ 
    cout << "Now is the time for all good men to come to the aid of their party." << endl; 
} 

if (wordCode == 2) 
{ 
    cout << "Now is the time for all good men to come to aid the aid of their country." << endl; 
} 

} 

「您尚未輸入有效的選擇。」 「請注入1或2」。

無論選擇什麼值,上述文本都會重複。

回答

3

爲什麼要這樣呢?

while (wordCode >= 1 || wordCode <= 2) 

用戶輸入:

  wordCode >= 1  wordCode <= 2    
1    True    True   -> True || True -> True 
-1    False    True   -> False || True -> True 
2    True    True   -> True || True -> True 
3    True    False   -> True || False -> True 
999999   True    False   -> True || False -> True 
-99999   False    True   -> False || True -> True 

無論用戶輸入什麼號碼,病情可以從字面上永遠不會成爲虛假。

0

變化

while (wordCode >= 1 || wordCode <= 2) 

if (wordCode == 1 || wordCode == 2) 

你不想要的那部分循環;外層do/while處理就好了。你只需要輸出一次消息。

+0

這與'if(true)' – 2014-10-07 21:38:39

+0

糟糕有何不同。接得好 – 2014-10-07 23:05:48

0

爲了增加馬克B的答案,我想你想while (wordCode == 1 || wordCode == 2)

0

更改 「而(wordCode> = 1 || wordCode < = 2)」 至「,而(wordCode> = 1 & & wordCode < = 2 )」。這應該可以解決你的問題。