The problems arise because of the sequence in which you read, display and check for end of file.
Look at function
FindContact()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void FindContact(){
readFrom.open(fileName.c_str());
if(readFrom.fail()){
cout << "Cannot open file." << endl;
}
else{
cout << "Enter name: " << endl;
cin >> TargetName;
cout << "---------------------------------------" << endl;
while(!readFrom.eof()){
readFrom >> firstName >> lastName >> Number >> emailID;
if(firstName.compare(TargetName)==0){
cout << "Found details about " << TargetName << endl;
cout << firstName << " "<< lastName << " "
<< Number << " " << emailID << endl;
}
}
readFrom.close();
}
}
|
First time around. Line 12, check eof. Well, the file was only just opened, so its not eof.
Line 13 read the details.
Assume we have a match, lines 15 and 16 display the details.
Around the loop a second time. Check eof, it's still not eof.
line 13, read the details. Now we get end-of-file == true.
but we don't check it.
Instead, proceed to lines 15 and 16 and output the details again.
Around the loop again. This time eof is true.
Also note that when the read file is unsuccessful, the existing values in the various strings remain unaltered. In addition, the fail() flag is set, which persists until it is cleared.