2016-10-25 28 views
1

我希望查找變量「檢查」的確切匹配。如果用戶鍵入「type o」或「type b」,循環將結束。我試過while (check != "type o"){...},它工作,但沒有第二個條件。我很困惑。以下是我的代碼。C++多個條件匹配確切的字符串

void sunTypeCheck(string sunCheck){ 
    string check = sunCheck; 

    transform(check.begin(), check.end(), check.begin(), ::tolower); 

    while (check != "type o" || check != "type b"){ //This is the problem. 
     cout << "Please enter a valid type of Sun. Try again: "; 
     getline(cin, check); 
     transform(check.begin(), check.end(), check.begin(), ::tolower); 
    } 
} 

這是我的主要方法。

int main(){ 
cout << "Please enter sun type: "; 
     getline(cin, typeOfSun); 
     sunTypeCheck(typeOfSun); 
} 

任何幫助將不勝感激。我看網上,並嘗試使用「比較」但只要我包括第二個條件,它不會工作,並計劃將始終返回Please enter a valid type of Sun. Try again:

+0

想一想'||'(或)做了什麼。如果一方是'真',那麼這個表達所評估的是什麼? – NathanOliver

+1

如果'check'不是''type o「'***和*** not'」type b「',那麼你希望條件成立?請學習基本[布爾代數](https://en.wikipedia.org/wiki/Boolean_algebra)。 –

回答

2

當條件變爲false時while循環中斷。

check != "type o" || check != "type b" 

注:
||當其中一個條件返回true時返回true ,如果兩個條件都爲false,則返回false。

所以可以說你進入了「O型」 這將是這樣的:

"type o" != "type o" || "type o" != "type b" 

的首要條件返回false,第二個會返回true。

false || true 

所以我說什麼時,條件之一?運算符返回true?是的,這是真的。

所以要解決這個問題,你必須使用& &操作

while(check != "type o" && check != "type b") 

編輯: 爲& &操作時的條件之一是假的,返回true,則返回false當且僅當這兩個條件是真的。

+0

哦我明白了!感謝你們!!你的解釋是最容易閱讀的! – JamesPoppycock

1
while (check != "type o" && check != "type b") 
+0

這解決了這個問題,但添加一些解釋永遠不會傷害任何人;) – Treycos

2

讓我們將去摩根定律,看看我們有什麼:

check != "type o" || check != "type b" 

被equivalnet到:

!(check == "type o" && check == "type b") 

所以循環將只要繼續check不等於兩個字符串同時。這當然是事實,因爲字符串是不同的。

1

如果你很難了解病情負邏輯,正取代它:

while (true) { 
    if(check == "type o" || check == "type b") break; 
    ... 
} 

同樣的模式會在你的情況下非常有用解決您的程序邏輯 - 你不應該有代碼,該代碼多次執行相同的操作(您的案例中的getlinetransform重複)。另外,當您嘗試修改函數中的值時,您可以修改本地副本。所以更好的實施將是:

std::string getTypeOfSun() 
{ 
    string sun; 
    while(true) { 
     cout << "Please enter a type of Sun: "; 
     getline(cin, sun); 
     transform(sun.begin(), sun.end(), sun.begin(), ::tolower); 
     if(sun == "type o" || sun == "type b") 
      break; 
     cout << "Invalid type of Sun, try again..." << endl; 
    } 
    return sun; 
} 


int main(){ 
    string typeOfSun = getTypeOfSun(); 
    ... 
}