searching text file

closed account (1vf9z8AR)
function Searchf accepts line but displays not found even for words that are present.
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
  #include<iostream>
#include<stdlib.h>
#include<fstream>
#include<string>
using namespace std;
char line[80];
void write()
{
    char ch;
    ofstream w1;
    w1.open("text.txt");
    do
    {
        cout<<"Enter line(dot to terminate)"<<endl;
        cin.getline(line,80,'.');
        w1<<line;
        cout<<"More lines?(y/n)";cin>>ch;cout<<endl;
    }while(ch=='y');
    w1.close();
}
void read()
{
    ifstream r1;
    r1.open("text.txt");
    while(!r1.eof())
    {
        r1>>line;
        cout<<line<<endl;
    }
    r1.close();
}
void searchf()
{
    string line;
    string s;
    cout<<"Enter line to search";cin>>line;
   cout<<endl;
   ifstream f1;
 while(!f1.eof())
 {
     f1>>s;
     if(s==line)
        cout<<"Word found"<<endl;
     else
        cout<<"Not found"<<endl;
 }
   }
int main()
{

    int n;
    char ch;
    do
    {
    cout<<"1-write file"<<endl;
    cout<<"2-read file"<<endl;
    cout<<"3-search file"<<endl;
    cout<<"Enter option:";cin>>n;cout<<endl;
    if(n==1)
        write();
    else if(n==2)
        read();
            else if(n==3)
                searchf();
    else
        cout<<"Enter correct option!!"<<endl;
    cout<<"Do you want to continue(y/n)?";cin>>ch;
    cout<<endl;
    }while(ch=='y');
}
Last edited on
In the search function, the file is not opened. Also, it is not a good idea to use eof() as the loop condition, it can give unexpected results. Better to test the result of actually reading the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void searchf()
{
    string line;
    string s;
    cout << "Enter line to search "; 
    cin  >> line;
    cout << endl;
    
    ifstream f1("text.txt");
    bool found = false;
    
    while ( f1 >> s )
    {
        if (s==line)
        {
            cout << "Word found" << endl;
            found = true;
        }
    }
    
    if (!found)
        cout << "Not found" << endl;
}
closed account (1vf9z8AR)
thank you so much.
Topic archived. No new replies allowed.