File manipulation in C++, retrieving data from file

Hello everybody. I have a program that saves some data got from user. So it's necessary to save in a file, which I didn't have any trouble.
The problem I found is when I need to retrieve the data from the file .txt made by the program.
I use a while loop using the following:
1
2
3
4
5
6
7
ifstream read("myfile.txt");

while(!read.eof())
	{
          read>>code>>name>>year>>semester;

        }

I've saved with spaces between the data.

The problem I face is when I retrieve the data, the last one is duplicated.
What's wrong?

Best regards.
Last edited on
The problem I face is when I retrieve the data, the last one is duplicated.
What's wrong?

The problem is with your loop condition

while(!read.eof())

Essentially, the end of file bit is triggered only after the end of file character is read. You could change your loop to this:

1
2
3
while( read>>code>>name>>year>>semester )
{
}


and the last data should not be duplicated. The above loop condition will return false if the end of file is about to be read which is more useful than checking if it was just read.
Thank you man!
Worked very nice!
Topic archived. No new replies allowed.