searching text file

closed account (1vf9z8AR)
The read and write work fine but search always gives "not found".

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
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
    char name[80];
    int rno;
};
int main()
{
        student s1;
    int option,n;
    cout<<"Enter 1 to write file\nEnter 2 to read file\n3 to search file";cin>>option;
    if(option==1)
    {
    ofstream f1;
    f1.open("file.dat",ios::binary);
    cout<<"Enter number of customers";cin>>n;
    for(int i=0;i<n;i++)
    {
    cout<<"\nEnter name(dot to terminate)";cin.getline(s1.name,80,'.');
    cout<<"\nEnter roll number";cin>>s1.rno;
        f1.write((char*)&s1,sizeof(student));
    }
      f1.close();
    }

    else if(option==2)
    {
           ifstream r1;
           r1.open("file.dat",ios::binary) ;
                while(   r1.read((char*)&s1,sizeof(student)))
           {
           cout<<"Name"<<s1.name<<endl;
           cout<<"Roll number"<<s1.rno<<endl;
           }
           r1.close();
    }

    else if(option==3)
    {
        int rno;
        cout<<"Enter roll number to search for";cin>>rno;
       bool condition=false;
        ifstream a1;
        a1.open("text.dat",ios::binary);

        while( a1.read((char*)&s1,sizeof(student)))
    {
        if (rno==s1.rno)
                {
                    condition=true;
                    cout<<"Name:"<<s1.rno<<endl;
                    cout<<"Roll number"<<s1.rno<<endl;
                };
    }
    if(condition==false)
    cout<<"Not found"<<endl;
    }

               return 0;
}
Last edited on
the search approach looks ok, so you will need to debug it.
put an else on it that prints rno and s1.rno when it fails, maybe only the first time this happens, then search for the first record. See what you get and why it did not match. Use that to figure out what is wrong.

Why do you search a file called text.dat when you write the data to a file called file.dat ?
Why don't you check that the file a1 is actually open ?
closed account (1vf9z8AR)
ooh thx guys.Obviously the file names had to be same.It didnt strike me.
Topic archived. No new replies allowed.