I wrote a simple program that accepts data and stores in a file and then displays it, but it is not producing correct output. The while(fin) loop seems to run more than i want it to.
I think it can be solved by keeping a count of number of records added, but is there any other way? Please Help Me!
/*Get name, roll number and marks of students of a class and store them in a file
and then display the contents*/
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
char name[25],ch='y',temp;
int roll;
//File looks like
float marks; //\nname1\nroll1\nmarks1\nname2\nroll2\nmarks2
ofstream fout("student.dat",ios::out);
while(ch=='y'||ch=='Y')
{
cout<<"\nEnter the name : ";
cin.getline(name,25);
cout<<"\nEnter the roll number : ";
cin>>roll;
cout<<"\nEnter the marks : ";
cin>>marks;
fout<<"\n"<<name<<"\n"<<roll<<"\n"<<marks;
cout<<"\nDo you want to enter more? (y/n) : ";
cin>>ch;
cin.get(temp);//to empty the stream of /n
}
fout.close();
cout<<"\nDo you want to view the contents of the file? (y/n) : ";
cin>>ch;
if(ch=='n'||ch=='N')
return;
ifstream fin("student.dat",ios::in);
while(fin)
{
fin.get(temp);//takes the newline before name
fin.getline(name,25);
cout<<"\nName : "<<name;
fin>>roll;
cout<<"\nRoll Number : "<<roll;
fin>>marks;
cout<<"\nMarks : "<<marks;
}
fin.close();
getch();
}