how to search a word in text file and print on screen

my question is simple ..
how to program to search for a word in a text file that already exists ans if that specific word is found anywhere in the text the entire line containing that word to be print on the screen.

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct student
{
    int reg;
    string name;
    string semester;
    int gpa;
};
int main()
{
 student stud;
 ofstream out;
 ifstream in;

 out.open("record.txt", ios_base::app);
 cout<<" \n select a choice from below  \n";
 cout<<"1. add a new student"<<endl;
 cout<<"2. delete student record"<<endl;
 cout<<"3. view all students information"<<endl;
 cout<<"4. search a student "<<endl;

 int choice;
 cin>>choice;
 if(choice==1)
 {
             cout<<"enter the registration number :";
     cin>>stud.reg;
             cout<<"enter name :";
             cin.ignore();
     getline(cin,stud.name);
             cout<<"enter semester :";
     getline(cin,stud.semester);
             cout<<"enter GPA :";
     cin>>stud.gpa;

     out<<stud.reg<<"\t"<<stud.name<<"\t"<<stud.semester<<"\t"<<stud.gpa<<"\n";
     out.close();

 }

 if(choice==3)
 {
     string line;
     in.open("record.txt");

     while(getline(in,line))
        {
            cout<<line<<endl;
        }
    in.close();
 }

if(choice==4)
 {
    string look_for, line,line2;
    in.open("record.txt");
    cout<<"what is registration no of student ?";
    cin>>look_for;
    if(!in.is_open())
     {
         cout << "Could not open file" << endl;
     }
    while(getline(in,line))
    {
    if(line.find(look_for)!= string::npos)
    {
    cout<<" record found "<<endl<<endl;
    break;
    }
    else cout<<"record not found ";
     }

    }

}
While searching for a word in a string (sentence) bear in mind words might appear at beginning, middle or end of sentences with corresponding upper/lower case and punctuation issues. You haven't shared your .txt file, so it's difficult to say anything more specific but here is an approach using std::regex – read the file line by line into a string with getline() and for each line apply the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string line{"It is a category!?"}; //read file line by line with getline() into this string

    std::regex r{"\\b(catEgory)\\b", std::regex_constants::icase};
    //search word (here actually 'category'), with word boundaries and isocase flag (case insensitive)
    //basic intro to C++11 regex: http://www.cplusplus.com/reference/regex/ECMAScript/
    //regex cheat-sheet: http://cpprocks.com/files/c++11-regex-cheatsheet.pdf

    if(std::regex_search(line, r))std::cout << line << "\n";
}

Looking around noticed that C++17 makes avalable the std::boyer_moore_searcher which is also widely used: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm but I don't have the required complier with me at the moment:
http://en.cppreference.com/w/cpp/utility/functional/boyer_moore_searcher
this is the .txt file and my aim is to search for a (reg#) number if it matches it means record found and the program should cout the whole line.,....




Reg#		Name			semester	GPA
3955		kaleem khattAK		34		9
14435		shin shina		2nd		4
4545		khan khan		3rd		2
3452		noor din		7th		2
You were pretty close, however if you didn't find it on the first line you gave up.
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool found = false;
    while (getline(in, line))
    {
      if (line.find(look_for) != string::npos)
      {
        cout << " record found " << endl;
        cout << line << "\n";
        found = true;
        break;
      }
    }
    if (!found)
      cout << "record not found ";
Thomas: this can lead to false positives:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    std::string line = "39555		kaleem khattAK		34		9";

    std::string word = "3955";


    if(line.find(word) != std::string::npos)std::cout << "found \n";
}

Seeing the shape of the file perhaps using a struct would be best

gunnerfunner,
I agree. It can lead to false positives, but this looks like an exercise to me so only a simple solution is required.
Sure the best would be to create a struct student, overload some operators and store it in a set or vector.
It already looks like you're searching the file for the registration number, so it looks like you only need to print the line when you find the number in the line, unless there is another problem.




so it looks like you only need to print the line when you find the number in the line, unless there is another problem.

well, there is at least another obvious problem as described in the previous two posts
Last edited on
ok the next thing i want to do is to detect a certain string in a line and delete that whole line....
could anyone help?
A trick to avoid finding false positives. Look for the registration number at the beginning of the line, and followed by a tab:
...
look_for += '\t'; // search for the registration number followed by tab
...
if (line.find(look_for) == 0) {
cout << "Record found\n";
....
}

As for deleting a line, you'll have to:
1. open a temporary file.
2. go through your text file, copying all records to the temp file except for the one you want to delete.
3. Close the temp file and the input file.
4. Rename the temp file to be your input file.
ok i understand the above steps but how would i implement step 3 and 4 and is there any way to program to delete the unwanted previous file
could some one tell me how could i interchange the temp.txt file with my input file...
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
#include <iostream>
#include <string>
#include <fstream>
#include <sstream> // for testing

// return true if the line starts with the registration number
// note: leading white space is ignored
bool has_reg_number( const std::string& line, int reg_number )
{
    // http://en.cppreference.com/w/cpp/string/basic_string/stol
    try { return std::stoi(line) == reg_number ; }
    catch( const std::exception& ) { return false ; }
}

std::ostream& copy_selected( std::istream& in, int reg_number, std::ostream& out = std::cout )
{
    std::string line ;
    while( std::getline( in, line ) )
        if( has_reg_number( line, reg_number ) ) out << line << '\n' ;
    return out ;
}

std::ostream& copy_not_selected( std::istream& in, int reg_number, std::ostream& out = std::cout )
{
    std::string line ;
    while( std::getline( in, line ) )
        if( !has_reg_number( line, reg_number ) ) out << line << '\n' ;
    return out ;
}

int main()
{
    // use a string stream for testing
    std::istringstream file ( "Reg#    Name            semester GPA\n"
                              "3955    kaleem khattAK  34       9\n"
                              "14435   shin shina      2nd      4\n"
                              "4545    khan khan       3rd      2\n"
                              "1443    not shin shina  2nd      4\n"
                              "3452    noor din        7th      2\n" );

    // print matching records
    copy_selected( file, 14435 ) ;

    file.clear() ;
    file.seekg(0) ;
    std::cout << "---------------------------\n" ;

    // delete records
    {
        std::ofstream new_file( "modified.txt" ) ;
        copy_not_selected( file, 14435, new_file ) ;
    }

    // verify that the new file was created correctly
    std::cout << std::ifstream( "modified.txt" ).rdbuf() ;
}

http://coliru.stacked-crooked.com/a/8083e364ab632be9

Unless the file contains many millions of lines, read the contents of the file into a container (vector), make all the additions/deletions/modifications to the items in the container, and finally write the contents of the container back into the file.
how some onee tell how to rename the file or swap their names?
Topic archived. No new replies allowed.