find word in a file and where it is .

hi
i wont to write a program to find a word from a file and cout which line the word in i can find the word but i can't find which line it is in.
can anyone help me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    int i=0;
    string word="<string>";
    string line;
    ifstream file("new.txt");
    if (file.fail())
        {
                cout << "error opening file" << endl;
                return 1;
        }
    while(!file.eof())
        {
            i++;
            string testWord;
            file >> testWord;
            cout<<testWord<<endl;
            if (testWord==word)
               {
                    cout<<"i found it "<<endl;
                    break;
                }

        }
    file.close();
    cout<<i<<endl;
    return 0;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

int main()
{
    const std::string word = "<string>" ;
    const char* const file_name = __FILE__ ; // "new.txt"

    std::ifstream file( file_name ) ;

    int line_number = 1 ;
    std::string line ;

    // http://www.cplusplus.com/reference/string/string/getline/
    while( std::getline( file, line ) ) // for each line in the file
    {
        // check if the word exists in the line
        // many ways to do this; the simplest is perhaps to use a string stream
        // http://www.artima.com/cppsource/streamstrings3.html
        std::istringstream stm(line) ;
        std::string test_word ;
        while( stm >> test_word ) // for each word in the line
        {
            if( test_word == word )
            {
                std::cout << "found it in line " << line_number << "\n\t"
                           << line << '\n' ;
                break ;
            }
        }

        ++line_number ;
    }

    // test case: <string> (this line should be printed just once) <string>
}

http://coliru.stacked-crooked.com/a/9480ba1d8d1a7602
thank you for helping
Topic archived. No new replies allowed.