Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you search a document for a string in c++?

Here's my code so far:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
    int count = 0;
    string fileName;
    string keyWord;
    string word;


    cout << "Please make sure the document is in the same file as the program, thank you!" 
         << endl << "Please input document name: " ;
    getline(cin, fileName);
    cout << endl;

    cout << "Please input the word you'd like to search for: " << endl;
    cin >> keyWord;
    cout << endl;
    ifstream infile(fileName.c_str());
    while(infile.is_open())
    {
        getline(cin,word);
        if(word == keyWord)
        {
            cout << word << endl;
            count++;
        }
        if(infile.eof())
        {
            infile.close();
        }

    }
    cout << count;

}

I'm not sure how to go to the next word, currently this infinite loops...any recommendation?

Also...how do I tell it to print out the line that that word was on?

Thanks in advance!

like image 375
Soully Avatar asked Feb 28 '23 06:02

Soully


2 Answers

while(infile >> word)
{
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}

This would do the job. Please read about streams more.

like image 69
Khaled Alshaya Avatar answered Mar 01 '23 20:03

Khaled Alshaya


If all you want to do is count the number of keywords in a file then:

int count = std::count(std::istream_iterator<std::string>(infile),
                       std::istream_iterator<std::string>(),
                       keyword);

If you want to read words.
But also want to print the line numbers then somthing like this should work:

std::string      line;
std::ifstream    infile("plop");
int              lineNumber = 0;

while(std::getline(infile, line)) 
{
    ++lineNumber ;
    std::stringstream   linestream(line);
    int hits = std::count(std::istream_iterator<std::string>(linestream),
                          std::istream_iterator<std::string>(),
                          keyword);
    if (hits != 0)
    {
        std::cout << "Line: " << lineNumber << "   Matches(" << hits << ")\n";
    } 
    count  += hits;
} 
like image 24
Martin York Avatar answered Mar 01 '23 20:03

Martin York