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!
while(infile >> word)
{
if(word == keyWord)
{
cout << word << endl;
count++;
}
}
This would do the job. Please read about streams more.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With