program not working (if else)

Hello everyone !
I am trying to create a function that reads a file which contains doctors record. If doctor id exists it shows doctor but if not then it should message "No record found". But it is not showing this error message.

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

void Doctor :: searchDoctor()
{
	int search;
	cout << "Enter id of doctor : ";
	cin >> search;
	ifstream searchDoctor;
	searchDoctor.open("Doctors.txt");
	searchDoctor >> dFirstName;
	searchDoctor >> dLastName;
	searchDoctor >> dAge;
	searchDoctor >> dID;
	searchDoctor >> qualification;
	searchDoctor >> dSpecialization;
	searchDoctor >> dExperience;
	while(!searchDoctor.eof())
	{
		if(dID == search)
		{
			cout << "\n\tName\t\tAge\t\tID\t\tQualification\t\tSpecialization\t\tExperience\n\n";
		    cout << "Dr. " << dFirstName << " " <<dLastName<<"\t\t" << dAge << "\t\t" << dID  << "\t\t    " << qualification << "\t\t\t" << dSpecialization << "\t\t     " << dExperience << " years"<<endl;
		}
		else
		{
			cout << "No record found...\n";
		}
	    searchDoctor >> dFirstName;
	    searchDoctor >> dLastName;
	    searchDoctor >> dAge;
	    searchDoctor >> dID;
	    searchDoctor >> qualification;
	    searchDoctor >> dSpecialization;
	    searchDoctor >> dExperience;
	}
	searchDoctor.close();
}
 
.eof isn't a good approach to files. be careful with it, there are many posts here on that issue if you want to search on it.

consider do-while to simplify this thing. then you wouldn't need to read the first record before looping.

consider a logic revision: you read a record, is it the one you wanted? No, tell user not found, search next guy, not him, tell again not found... found it.. output looks like
not found
not found
not found
not found
found blah blah blah this is your guy
not found
not found
not found
… etc

the if statement looks correct. what does it print when the doctor is not in the file?
it prints nothing
> it prints nothing

> searchDoctor.open("Doctors.txt");
This can fail, but you don't know that, because you don't check it.

> searchDoctor >> dFirstName;
Any of these could fail, but you don't know that, because you don't check it.

> while(!searchDoctor.eof())
If you're already at end of file, you're not going into the loop, even if you managed to read dID successfully.

Do you even call the function?

Is Doctors.txt really the filename? Beware of file explorer with it's "hide extensions of known file types" useless boondoggle.

Is the file in "the current directory"? This is a fluid concept depending on whether you run the program in the IDE, or by double-clicking on in in explorer (or even typing it's name on the command line).
Topic archived. No new replies allowed.