find word in file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • carly
    New Member
    • Oct 2006
    • 37

    find word in file

    Hi i have been trying to solve this question:

    Write a C++ program to find a given word in a file. It should display all the line numbers where the word occurs.

    i did this code:

    Code:
    #include <iostream>
    #include <conio.h>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
    string s1;
    ifstream in ("file.txt");
    int lines = 0;
    cout << "Enter your search string: " <<endl;
    cin >> s1;
    
    while(!in.eof())
    {
       in.seekg(0,ios::beg);
       lines ++;
       if(//String in file)
       {
                           
       cout<<"The  string occured at lines: " << lines<<endl;
      }
    }
    
    in.close();
    
    getch();
    return 0;
    }
    i just have problems in interpreting this part to code:
    if(//String in file), hope that someone can help me fix it.

    thanks

    carly
  • DemonPiggies
    New Member
    • Dec 2006
    • 8

    #2
    this site has info about the ios::beg
    http://www.cplusplus.c om/doc/tutorial/files.html
    it should be able to help you thru the search
    I've used those funct.'s before so I can't really help without rewrite the program
    but i'm assuming you need it to work with the one you posted right?

    Comment

    • DemonPiggies
      New Member
      • Dec 2006
      • 8

      #3
      it also covers the " in.seekg(0,ios: :beg) "
      which you'll probably use to read each line and then maybe dump it in to a string (which might be easier to compare) and compare sl ( the user's string) with each character in the file...
      like if( sl[x] == (Character from File) )...
      well something like that, just make sure you add so error coding tho...

      Comment

      • carly
        New Member
        • Oct 2006
        • 37

        #4
        Originally posted by DemonPiggies
        this site has info about the ios::beg
        http://www.cplusplus.c om/doc/tutorial/files.html
        it should be able to help you thru the search
        I've used those funct.'s before so I can't really help without rewrite the program
        but i'm assuming you need it to work with the one you posted right?
        ummm... I only needed help in writing this part to code:
        Code:
        if(//String in file)
        , the tutorials you gave me didnt really help me in figuring out how i can translate that sentence to code, but thanks anyway

        carly

        Comment

        Working...