2016-02-02 225 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