c++ - Boolean operator problems -
simple code here, i'm trying write code can pick on specific keywords, i'm not having lot of luck. here's code:
#include <iostream> int main(){ std::string input; bool isunique = true; std::cout<<"please type 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 type in of 3 words (in if statement), you'll proper output program ("common"). however, if type else, you'll same exact output. if limit program search 1 word (ie: "the") , test it, works should, there 2 or more keywords, program lists "common". i've tried replacing or statements commas didn't anything. code i'm trying implement going have 50+ keywords i'm trying find efficient way search these words.
you have change:
if(input == "the" || "me" || "it")
to:
if(input == "the" || input == "me" || input == "it")
the way operator ||
works in a || b
each clause a
, b
evaluated (if ever) on it's own. b
not care context of a
.
so in case following 3 expressions might evaluated (the last 1 never):
input == "the"
"me"
"it"
the first 1 may or may not result in true
, second 1 will.
you can rewrite code to:
int main() { std::cout << "please type 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"; } }
or (using boost):
int main() { std::cout << "please type 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"; } }
Comments
Post a Comment