0

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

Debartha Paul
  • 212
  • 3
  • 11
  • Check the text file next time? This is one of those cases where _seeing is believing_ applies to an extent. :-) – TrebledJ Jan 18 '19 at 11:40
  • 1
    General advice, learn to use a debugger, and/or how to debug by comments. Given the answer by TrebuchetMS, you could have found out that the second while was entered several times by yourself, and that this does not match your text file. – Aziuth Jan 18 '19 at 11:46

0 Answers0