I wrote a program in c++ that will take the input from the user the roll number and marks of a student and store them in a file. Then the program will read the file and display the values one by one. The program is supposed to display the values until the end... It does display it...but the last value that is stored in the file gets repeated... May I ask where am I going wrong and what is the possible solution to this problem?
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("Marks.txt",ios::out);
char ans='y';
int rollno;
float marks;
while (ans=='y'||ans=='Y')
{
cout<<"\nEnter the roll no.: ";
cin>>rollno;
cout<<"\nEnter marks: ";
cin>>marks;
fout<<rollno<<'\n'<<marks<<'\n';
cout<<"\nWant to enter more records?(y/n)...";
cin>>ans;
}
fout.close();
ifstream fin;
int c;
fin.open("Marks.txt",ios::in);
while(!fin.eof())
{
fin>>c;
cout<<"\n"<<c;
fflush(stdin);
}
fin.close();
getchar();
return 0;
}
Suppose I've entered the roll number as 25 and marks as 58. Then comes the line asking me if I wish to enter more record or not. I entered 'N'. I expected the output to be like this: 25 58 But the actual output came out to be something like this: 25 58 58