2015-02-09 215 views
-5

我正在寫一個簡單的RPG遊戲控制檯遊戲,我將開發與圖形加班等,但現在我有我的問題。 .. while循環。我不會經常使用它們,但我認爲這對於這種必要性是有益的。基本上,我有一個開篇故事,然後給用戶4個選項,他們可以通過按下「1」,「2」,「3」或「4」來輸入。如果用戶輸入其他內容,則應顯示一條消息,並允許用戶鍵入正確的輸入。我的代碼如下:雖然條件沒有得到滿足,while ...循環仍然保持循環

int action; // Used to determine what the user wants to do. 
cout << "Story goes here\n\n"; 
cout << "What would you like to do? (1/2/3/4)\n\n"; 
cout << "1. Do this\n"; 
cout << "2. Do that\n"; 
cout << "3. Do this that\n"; 
cout << "4. Party\n\n"; 

cin >> action; 

do 
{ 
    switch (action) 
    { 
    case 1: 
     cout << "1\n"; 
     break; 
    case 2: 
     cout << "2\n"; 
     break; 
    case 3: 
     cout << "3\n"; 
     break; 
    case 4: 
     cout << "4\n"; 
     break; 
    default: 
     cout << "I'm sorry, but I'm not sure what you want to do. Please tell me again using the corresponding number. (1/2/3/4)\n\n"; 
     cin >> action; 
     break; 
    } 
} while ((action != 1) || (action != 2) || (action != 3) || (action != 4)); 
system("pause"); 

現在我測試過,如果我輸入5或6,它顯示默認的消息,讓我再試一次,不過,如果我鍵入的內容發生了1,2,3,或者4進入交換機並繼續輸出我打印出來的號碼。它永遠不會結束。我在MS Visual Studio 2013 Express中使用C++。

我還使用了調試器,它表示動作等於2(或任何我按下的數字),並繼續運行循環。我不知道爲什麼會發生這種情況。

+0

您的條件邏輯不正確 - 將所有「||」更改爲「&&」。 – 2015-02-09 07:57:35

+1

仔細想想,如果「行動」是「2」,條件將會評估什麼。 – juanchopanza 2015-02-09 07:58:58

回答

0

,而不是 「或」 條件try 「和」 條件 它能夠解決您的問題

2

變化

while ((action != 1) || (action != 2) || (action != 3) || (action != 4)); // (1) 

while ((action != 1) && (action != 2) && (action != 3) && (action != 4)); // (2) 

分析:

如果action == 1

(1)將計算爲

while(false || true || true || true) 

=>

while (true) 

(2)將計算爲

while(false && true && true && true) 

=>

while (false) 
+0

同時檢查'cin >> action'是否成功,否則它將不斷使用上次成功輸入的值。簡單的做法是'while(cin &&(action!= 1)&&'... – 2015-02-09 08:04:00

0

這很笨拙,因爲你基本上必須兩次測試條件。 (您的具體問題是布爾測試不正確:您需要&&而不是||)。

考慮使用功能,而不是內置的驗證:

int getAction(void) 
{ 
    for (;;)/*infinite loop idiom*/{ 
     int action; /*scope as local as possible*/ 
     cin >> action; 
     if (action >=1 || action <= 4){ 
      return action; /*this is ok, so return*/ 
     } 
     cout << "I'm sorry, but I'm not sure what you want to do. Please tell me again using the corresponding number. (1/2/3/4)\n\n"; 
    } 
} 
0

它只是暫停在默認的,因爲你所要求的輸入和分配的行動。

你應該真的在循環之前初始化動作。一旦行動被分配了1,2,3,4,它將永遠循環,因爲這就是代碼所要做的事情。你再也不會改變它的價值,所以while語句一直在旋轉。

在你的case語句中,你需要做任何需要的操作,如果你想退出循環,就在這個時候添加一個退出標誌。突破標誌着案件陳述的結束,以阻止它進入下一個案例。