Unexpected Output in reading/writing class objects

The output will most probably explain it
[Enter Name: Somebody
Enter Grade: A
Enter Marks: 100
Do you want to enter more? : Y
Enter Name:
Enter Grade: A]

Basically When the second time I add information, it doesn't take the name. This problem comes for me in nearly every program, but I don't know why. Please help me out.



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
53
54
55
56
57
58
59
60
61
62
63
  #include<fstream.h>
#include<conio.h>
#include<stdio.h>

class Student{
		char name[25];
		char grade;
		float marks;
		public:

		void get();
		void display();
		};

void Student::get()
{
	cout<<"\nEnter name: ";
	cin.getline(name,25);
	cout<<"\nEnter grade: ";
	cin>>grade;
	cout<<"\nEnter marks: ";
	cin>>marks;

}
void Student::display()
{
	cout<<"\nName: ";
	puts(name);
	cout<<"Grade: "<<grade;
	cout<<"\nMarks: "<<marks;
}

void main()
{
	clrscr();
	Student person;
	char choice='y';
	ofstream fout("afile.dat",ios::out|ios::binary);

	while(choice=='y'||choice=='Y')
	{
		person.get();
		fout.write((char*)&person,sizeof(Student));
		cout<<"\nDo you want to enter more? : ";
		cin>>choice;

	}

	fout.close();
	cout<<"\nNow displaying contents of the file: ";
	ifstream fin("afile.dat",ios::in|ios::binary);
	fin.seekg(0);
	while(1)
	{
		fin.read((char*)&person,sizeof(person));
		if(!fin)break;
		person.display();
	}
	fin.close();

	getch();

}



One more question I have is, that we have getline() and get() for input, what do we have for output?
The solution is: http://www.cplusplus.com/reference/istream/ws/

The problem is that the getline reads up to next newline.
If user hits Enter between 'y' and next name, then there is a newline before the name.
You could also try putting a cin.ignore() before the line that cause problem. I remember it solving those kind of problem when I had to do simple interfaces for school assignements.

Good luck and keep posting if you need help !
Last edited on
The ignore() discards anything. The std::ws discards only whitespace.

When the user may or may not add whitespace (like newline) between "data fields", the ws is more convenient.

When there is always an offending newline before getline() "data field" and the field has prefix whitespace that cannot be skipped, the ignore() is more convenient.
Thanks for the input @keskiverto !
Thank you very much, you solved a problem which was very annoying for me!
Since newline is the problem, I fixed it by adding cin.get(some_char_variable) to remove the newline.
Topic archived. No new replies allowed.