tags:

views:

114

answers:

4

Basically this program searches a .txt file for a word and if it finds it, it prints the line and the line number. Here is what I have so far.

Code:

#include "std_lib_facilities.h"

int main()
{
    string findword;
    cout << "Enter word to search for.\n";
    cin >> findword;

    char filename[20];
    cout << "Enter file to search in.\n";
    cin >> filename;
    ifstream ist(filename);

    string line;
    string word;
    int linecounter = 1;
    while(getline(ist, line))
    {
     if(line.find(findword) != string::npos){
             cout << line << " " << linecounter << endl;}
     ++linecounter;
     }

     keep_window_open();
}

Solved.

A: 

You could use a regular expression to find the word in the line. Don't know enough C++ to help you with the details.

pb
http://stackoverflow.com/questions/329517/there-is-a-function-to-use-pattern-matching-using-regular-expressions-in-c
Pukku
A: 

Make sure there are no spaces around the names in your text file. Otherwise, let ist take care like the following :

while(ist >> line)
{
 if(line == findword){
         cout << line << " " << linecounter << endl;}
 ++linecounter;
 }

I believe that your names file contains a name on every line. so using >>, ist will take care if there are extra spaces.

AraK
+1  A: 

I would do as you suggested and break the lines into words or tokens delimited by whitespace and then search for desired keywords amongst the list of tokens.

Twotymz
+4  A: 

You're looking for find:

if (line.find(findword) != string::npos) { ... }
Ben Straub
This is exactly what I was looking for. However I am still having a problem. It's outputting results that don't have the word in it. I didn't include the !- string::npos because I didn't know what you meant by it. I'll edit the code to show you what I have.
trikker
!= string::npos is the value you compare if the word is not present in the line. That is if the result returned by find is not equal to string::npos than that means that you have found the word, otherwise it will ignore the line
Milan
Forget it, I included the !- string::npos and it worked. I'll just do some research on it.
trikker
Thanks for the info Zka.
trikker