Searching for Keywords

Hey all, trying to write a tiny little script that can pick up on keywords, but I'm not having a lot of luck. Here's the code, I'll explain the problem after you take a look at it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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 you type in any of those three words, you'll get the proper output from the program. However, if you type anything else, you'll get that same exact output. If I limit the program to only search for one word (ie: "the") and then test it, everything works as it should, but as soon as there are two or more, it falls apart on me. Why is this and what can I do to search for multiple keywords? (The project I'm trying to implement this into is going to have 50+ keywords so I'm trying to find the most efficient way to do this).
Last edited on
1
2
3
if(input == "the" || "me" || "it"){
        isUnique = false;
    }

This is the same as
if((input == "the") || ("me") || ("it"))
Never actually used it like this but apparently any const char* like "me" or even "" will return true.

So you have to write your test like this
if(input == "the" || input == "me" || input == "it"

EDIT : figured it out i think. const char* even if it points to empty string is still points to valid object. And if you test this pointer in if() statement you will always get true unless its 0 or nullptr


You could put those words in std::vector<std::string> vec and than
1
2
3
4
5
6
for(int i = 0; i < vec.size(); ++i){
    if(vec[i] == input){
        isUnique = false;
        break;    //exit for loop
    }
}
Last edited on
To let more words be written and evaluated, use getline(std::cin,input); in the #include <string> library. std::cin evaluates whitespace as a null termination, so it won;t work for more than one word.
Thanks a lot for the help guys!
Topic archived. No new replies allowed.