bontoo
bontoo

Reputation: 137

Word search in C++

I made a code which finds a word in a text file. The code works fine but the problem is that i need to search if the exact word is existed or not but it gives the same result even if it just part of another word. Example im looking for the word 'Hello' but it says already existed cos the txt file has the word 'Hello_World' which is not the same but includes it. How can i check for the exact word and ignore the others. Im thinking to do something with the length of the word and ignore anything longer but not sure. The code is here:

cout << "\n Type a word: ";
    getline(cin, someword);

    file.open("myfile.txt");

    if (file.is_open()){
        while (!file.eof()){
            getline(file, line);
            if ((offset = line.find(someword, 0)) != string::npos){

                cout << "\n Word is already exist!! " << endl;
                file.close();
            }
        }
        file.close();
    }

Upvotes: 0

Views: 544

Answers (2)

AKJ88
AKJ88

Reputation: 733

Use this code to split words and search for the intended one:

#include <sstream>

stringstream ss(line);
while (getline(ss, tmp, ' ')){
    if (tmp == someword){
        //found
    }
}

Upvotes: 1

Don Reba
Don Reba

Reputation: 14051

string line;
getline(file, line);

vector<string> words = TextToWords(line);
if (find(words.begin(), words.end(), someword) != words.end())
    cout << "\n Word already exists.\n";

The TextToWords implementation is up to you. Or use a regular expression library.

Upvotes: 2

Related Questions