Writing to a file duplicates the last entry

72 Views Asked by At

I think this is the only lines of code needed. The program reads from a text file, separates the information out and rewrites it to two different files. It "correctly" reads all the values, and separates it appropriately. the issue I am having, is in the files for output it duplicates the last entry to the file. I know how to solve this if I am using getline() for the input, but I am reading in each individual word separately in the file.

Here is the code for where I think the issue is:

while (in_file.peek() != EOF)
{
     in_file >> rank >> boy_name >> boy_number >> boy_percent >> girl_name >> girl_number >> girl_percent;
     boy_output << rank << " " << boy_name << " " << boy_percent << endl; 
     girl_output << rank << " " << girl_name << " " << girl_percent << endl;
}

I used while (getline(in_file, line) && in_file.peek() != EOF) in a similar program, but like I said I was reading the information in line by line, instead of the word seperation.

Thanks

2

There are 2 best solutions below

0
JustVirtually On

You can try using -

while(1)
{
    if(in_file.peek() == EOF)
    {
        break;
    }
    in_file >> rank >> boy_name >> boy_number >> boy_percent >> girl_name >> girl_number >> girl_percent;
    boy_output << rank << " " << boy_name << " " << boy_percent << endl; 
    girl_output << rank << " " << girl_name << " " << girl_percent << endl;
}
0
Blastfurnace On

The simplest way to correct your input loop is:

while (in_file >> rank >> boy_name >> boy_number >> boy_percent >> girl_name >> girl_number >> girl_percent)
{
     boy_output << rank << " " << boy_name << " " << boy_percent << endl; 
     girl_output << rank << " " << girl_name << " " << girl_percent << endl;
}

This will loop as long as the stream extraction succeeds. This correctly handles both EOF and mismatches between the input data and your variable types.