-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq2.cpp
45 lines (45 loc) · 1.5 KB
/
q2.cpp
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
#include<bits/stdc++.h>
using namespace std;
const string filename="courses.txt";
int main()
{
fstream file;
file.open(filename,ios::in);
if(file.is_open())
{
string str;
cout<<"Enter a search string: ";
getline(cin,str);
// for temporarily storing each line of text and count
string line;
int count=0;
while(getline(file,line))
{
bool matched=false;
for(int i=0;i+str.length()<=line.length();i++)
{
// compare returns 0 only if matches perfectly
if(line.compare(i,str.length(),str)==0)
{
// found a match
matched=true;
break;
}
}
if(matched)
{
// print the match and increment count
cout<<line<<endl;
count++;
}
}
file.close();
cout<<"Number of matches: "<<count<<endl;
}
else
{
cout<<"Error opening the file"<<endl;
return 1;
}
return 0;
}