Search word in more than one text file

closed account (iN8poG1T)
Hi, is anyone know how to search two text file and the output will be
- show which text file
- line number
- the word itself

currently what i did is i need the user to key in the text file. i dont want to do that, i want it to be

search word : small

and it will show the
filename
line no
small (which the word i search)

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int searchWord()
{
   string input_file,searchWord,line;
   while (1)
    {
        int line_Number=0,found=0;
        cout<<"File: ";
        getline(cin,input_file);
        if (input_file == "exit")
        break;

        cout<<"Search Word: ";
        getline(cin,searchWord);
        ifstream file(input_file.c_str());
        if(file)
        {
            while(getline(file,line))
            {
                line_Number++;
                int position=0;
                for(int i=line.find(searchWord); i<line.length(); i=i+position)
                {
                    position=line.find(searchWord,i);
                    if(position != string::npos)
                    {
                        cout<<endl<<searchWord<<" is at line "<<line_Number<<endl;
                        found=1;
                    }
                    else break;
                }
            }
            file.close();
            if(found==0)
            {
                cout<<endl<<searchWord<<" not in file"<<endl;
            }
        }
        else
        {
            cout<<endl<<input_file<<" not found" <<endl;
        }

}
}
int main()
{

    searchWord();

    return 0;

}


my text file is below

file1

The study is published in the journal Nature Climate Change.
It focuses on the Scotia Sea and the Antarctic Peninsula - the places
where the crustaceans are most abundant.

file2

The team's analysis indicates the centre of krill distribution has now
moved to where more favourable conditions are found, tracking
southward towards the Antarctic continent by about 440km, or four
degrees of latitude.
Last edited on
In other words, you are writing a simple variant of findstr | grep.
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
https://linux.die.net/man/1/grep
findstr /n small file*
grep  -n small file*

These programs handle command line arguments.
See http://www.cplusplus.com/articles/DEN36Up4/
Topic archived. No new replies allowed.