2016-07-06 60 views
-1

無論我輸入什麼,在此函數中唯一識別的int是1. 如果選擇了其他任何內容,則重複執行do-while循環。該代碼在沒有任何OR操作符的情況下也工作正常,例如, 「而(輸入!= 0)」只識別int輸入爲1

void menu() 
{ 
    int input = -1; 
    do 
    { 
    cout << "   ---------------" << endl << "   -  OU6  -" << endl << "   ---------------" << endl; 
    cout << "1. Read a transaction from the keyboard." << endl; 
    cout << "2. Print all transactions to console." << endl; 
    cout << "3. Calculate the total cost." << endl; 
    cout << "4. Get debt of a single person." << endl; 
    cout << "5. Get unreliable gold of a single person." << endl; 
    cout << "6. List all persons and fix." << endl; 
    cout << "0. Save and quit application." << endl; 
    cin >> input; 
    } while (input != (0 || 1 || 2 || 3 || 4 || 5 || 6)); 

    if (input == 0) 
    { 
     cout << "0!" << endl; 
     cin.get(); 
    } 

    if (input == 1) 
    { 
     cout << "1!" << endl; 
     cin.get(); 
    } 

    if (input == 2) 
    { 
     cout << "2!" << endl; 
     cin.get(); 
    } 
} 

回答

11

這條線:

while (input != (0 || 1 || 2 || 3 || 4 || 5 || 6)) 

沒有做什麼,你認爲它。你不能像這樣組合測試。你寫的東西基本上相當於while (input != true),並且由於true等於1,所以你可以看到唯一可行的選項是input == 1

您需要將其更改爲例如

while (input < 0 || input > 6) 
3

您在比較input0 || 1 || 2 || 3 || 4 || 5 || 6

||的結果是一個布爾值,一個真值。

0 || 1 || 2 || 3 || 4 || 5 || 6 

相當於

0 != 0 || 1 != 0 || 2 != 0 || 3 != 0 || 4 != 0 || 5 != 0 || 6 != 0 

其是(希望明顯)真。

而一個bool可以隱式轉換爲int,並true轉換爲1,所以這是你的唯一有效的輸入的理由;您的狀況相當於input != 1

翻譯成邏輯的英文短語「如果輸入不是0或1」是「如果輸入不是0 輸入不是1」。

這將使你

while (input != 0 && input != 1 && input != 2 && input != 3 && input != 4 && input != 5 && input != 6) 

這是一個嚴重的混亂,以及更明智的事,可以是

while (input < 0 || input > 6) 

,或者更迂迴,

while (!(input >= 0 && input <= 6)) 
+0

我喜歡關於測試爲何做什麼它做額外的細節。 – Almo

0

正如其他已經指出,使用|| (邏輯或)將使您的條件相當於(input != 1)

我建議在這裏使用一個開關/ case語句和一個附加條件:

void menu() 
{ 
    int input = -1; 
    bool inputIsValid = false ; 
    do 
    { 
     cout << "   ---------------" << endl << "   -  OU6  -" << endl << "   ---------------" << endl; 
     cout << "1. Read a transaction from the keyboard." << endl; 
     cout << "2. Print all transactions to console." << endl; 
     cout << "3. Calculate the total cost." << endl; 
     cout << "4. Get debt of a single person." << endl; 
     cout << "5. Get unreliable gold of a single person." << endl; 
     cout << "6. List all persons and fix." << endl; 
     cout << "0. Save and quit application." << endl; 
     cin >> input; 

     switch (input) 
     { 
     case 0: 
      cout << "0!" << endl; 
      cin.get(); 
      inputIsValid = true; 
     break; 

     /* other cases here... */ 

     default: 
      inputIsValid = false ; 
     break; 
     } 
    } while (false == inputIsValid) ; 
}