2012-10-28 70 views
3

在我的代碼中,即使輸入'Q'或'q',程序仍然會循環顯示菜單。這裏有什麼問題?下面是代碼:C++菜單中的循環

{ 
    char selection; 
    do { 
     cout << "Add a county election file   A" << endl; 
     cout << "Show election totals on screen  P" << endl; 
     cout << "Search for county results   S" << endl; 
     cout << "Exit the program     Q" << endl; 
     cout << "Please enter your choice: "; 
     cin >> selection; 
    } while ((selection != 'Q' || selection != 'q')); 
    return 0; 
} 
+0

如果輸入'q','selection!='Q''爲true。如果你輸入'Q',另一個是真的......所以沒有辦法離開這個循環。 – Mat

+0

你是第一次說話嗎? –

+3

經典錯誤'選擇!='Q'||選擇!='q''應該是'選擇!='Q'&&選擇!='q'' – john

回答

11

你想使用AND(&&)運營商在測試,而不是或(||)運算符。否則,selection != 'Q'selection != 'q'之一將始終爲真,並且您的循環將永遠不會退出。

3

正如指出的那樣,||不符合您的要求。您需要使用&&運營商。

如果你按q,那就是這種情況。

(selection != 'Q' || selection != 'q') 
|---------------| |--------------| 
    true     false 

如果你按Q,那就是這種情況。

(selection != 'Q' || selection != 'q') 
|---------------| |--------------| 
    false     true 

循環應該是這樣的。

while((selection != 'Q' && selection != 'q')); 
2

試試這個:

} while((selection != 'Q' && selection != 'q')); 
0

使用toupper()

如果你這樣做,while (toupper(selection) != 'Q' )你不需要檢查大寫和小寫。

#include <iostream> 
#include <stdio.h> 
using namespace std; 

int main(void) 
{ 



    char selection; 
    do { 
     cout << "The Menu" << endl; 
     cout << "____________________________________" << endl; 
     cout << "Add a county election file   A" << endl; 
     cout << "Show election totals on screen  P" << endl; 
     cout << "Search for county results   S" << endl; 
     cout << "Exit the program     Q" << endl; 
     cout << "____________________________________" << endl; 
     cout << "Please enter your choice: "; 
     cin >> selection; 
    } while (toupper(selection) != 'Q' ); 



    cout<<" \nPress any key to continue\n"; 
    cin.ignore(); 
    cin.get(); 

    return 0; 
}