Impossibility to search multiple strings in a file. txt

Asked

Viewed 22 times

0

I’ve been trying to make a program to which you search for several strings in a . txt in the c++ language but can only search for one string

My code:

       #include <iostream>
       #include <string>
       #include <fstream>
       using namespace std;

int main()
{

         ifstream input;
    size_t pos;
          string line;

    input.open("t.txt");
    if(input.is_open())
    {
        while(getline(input,line))
        {
         pos = line.find("hey");
          if(pos!=string::npos) // string::npos is returned if string is not found
    {
        cout <<"Found!";
        break;
    }
        }
    }
  • thanks, helped me a lot, I’m learning more and more about programming in this wonderful forum - Noob Zando

1 answer

0

A practical solution is to store the words of the archive in a map or in a set and then check directly, without having to browse each file line for each check.

A map or a set also guarantees you a very efficient search of words, if the key is the word itself.

Implementation with set:

#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <vector>

using namespace std;

int main() {
    ifstream input;
    set<string> words; //set para guardar todas as palavras do arquivo, sem repetições

    input.open("t.txt");
    if(input.is_open()) {
        string word;
        while(input >> word) { //percorrer palavra a palavra
            words.insert(word); //inserir a palavra
        }
    }

    vector<string> verifyWords = {"hey", "there", "people"}; //palavras a verificar
    for (auto word : verifyWords){ //para cada palavra
        if (words.find(word) != words.end()){ //se existe
            cout << word << " existe" << endl; //faz algo com ela
        }
    }
}

I chose to keep the names of the variables in English to be consistent with the ones I already had. Note also that I now read the file word by word instead of line by line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.