Program on reading writing data to file not working

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  /*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();
}
You have two problems.

First: mixing operator>> and getline() is a problem:

http://en.cppreference.com/w/cpp/string/basic_string/getline

Read the "Notes" section to see how to solve this.


Second: Testing for an error on line 40 is too late. What happens when the eof is detected on line 42?
Topic archived. No new replies allowed.