File display problem

Hi i guys i want to display all the contents of a file excluding one based on user input
say i have 4 records in the file numbered 1 to 4....the user chooses 2 to exclude it outputs records 1,3,4,4 when it should be records 1,3,4 what am i doing wrong here is the code.its basically displaying the last record in the file twice

void excludeRecord()
{

ifstream read;
read.open("Data.txt");

int recordC =0;
string fnameC = " ";
string lnameC = " ";
string addressC= " ";

int choice =0;

//file open test
if(read.fail() )
cerr << "Error Opening file" << endl;

cout << "Enter a record to exclude : " << endl;
cin >> choice;

//read while file contains data
while (!read.eof() )
{
// data from file stored in these variables
read >> recordC >> fnameC >> lnameC >> addressC ;

if(choice != recordC)
{
cout << recordC << " " << fnameC << " " << lnameC <<" "<< addressC <<endl;
}


} // while


}

Last edited on
The extractor does not set the eof bit on the stream until a read fails. When you read addressC for record 4, the read succeeds, so eof is not set. The loop continues, and the next time through, read.eof() remains false. When recordC is read the next time, the file is empty and eof is set. Because nothing is in the file, recordC, fnameC, lnameC and addressC are not modified, and you continue on in your code, when you print out record 4 information a second time. Then when you go back to the top of the loop eof is true, and you exit.

There are a number of ways to fix this. A couple that come immediately to mind:
(1) Check (!read.eof()) before checking (choice != recordC)
(2) Perform "read >> recordC >>..." before the while loop AND right at the end of the while loop. This guarantees that the read is always done before the eof check.

By the way, when you post code, pleas use code tags. Click the "<>" button in the Format selection and past your code between the tags. This will make it easier for us to read and comment on your code.
Typically we would do something like
1
2
3
4
5
6
7
8
//read while file contains data
while (read >> recordC >> fnameC >> lnameC >> addressC)
{
    if(choice != recordC)
    {
        cout << recordC << " " << fnameC << " " << lnameC <<" "<< addressC <<endl;
    }
} // while 
.
Topic archived. No new replies allowed.