2016-02-02 231 views
-2

簡單的代碼在這裏,我試圖寫一個代碼,可以拿起特定的關鍵字,但我沒有很多運氣。下面的代碼:布爾運算符問題

#include <iostream> 
int main(){ 
    std::string input; 
    bool isUnique = true; 

    std::cout<<"Please type a word: "; 
    std::cin>>input; 

    if(input == "the" || "me" || "it"){ 
     isUnique = false; 
    } 
    if(isUnique){ 
     std::cout<<"UNIQUE!!"<<std::endl; 
    } 
    else 
     std::cout<<"COMMON"<<std::endl; 
} 

如果您在任何這三個字的類型(if語句),你會得到從節目(「共用」)適當的輸出。但是,如果您鍵入其他任何內容,則會得到相同的確切輸出。如果我限制程序僅搜索一個單詞(即:「the」)然後再進行測試,那麼所有內容都可以正常工作,但只要有兩個或更多關鍵字,程序就會將所有內容都列爲「常見」。我也嘗試用逗號替換或聲明,但也沒有做任何事情。我試圖實現這個代碼將有50多個關鍵字,所以我試圖找到最有效的方式來搜索這些單詞。

+0

'如果(輸入== 「||」==「我」||輸入==「it」){'那簡單!從許多關鍵字中查找使用一個容器,並使用'std :: find()'。 –

+0

我建議你看看'||'是如何工作的。 –

+0

@πάνταῥεῖ非常感謝! –

回答

3

你只需要改變:

if(input == "the" || "me" || "it") 

到:

if(input == "the" || input == "me" || input == "it") 

的方式操作||作品A || B是每個子句AB評估(如果有的話),在它自己的。 B不關心A的上下文。

所以,你在你的情況下3周的表達可能被評估(最後從不之一):

  1. input == "the"
  2. "me"
  3. "it"

第一個可能會或可能不會導致true,但第二個肯定會。


您也可以重寫代碼到:

int main() { 
    std::cout << "Please type a word: "; 
    std::string input; 
    std::cin >> input; 

    auto common_hints = {"the", "me", "it"}; 
    if (std::find(begin(common_hints), end(common_hints), input) != end(common_hints)) { 
     std::cout << "COMMON\n"; 
    } else { 
     std::cout << "UNIQUE!!\n"; 
    } 
} 

Live demo

或(使用Boost):

int main() { 
    std::cout << "Please type a word: "; 
    std::string input; 
    std::cin >> input; 

    auto common_hints = {"the", "me", "it"}; 
    if (boost::algorithm::any_of_equal(common_hints, input)) { 
     std::cout << "COMMON\n"; 
    } else { 
     std::cout << "UNIQUE!!\n"; 
    } 
} 

Live demo