Problem with classes

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
#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
class student{

private:

	int roll;
	float marks[5];
	char nam[34];

public:

	void getData(int stud){

		cout<<"Please enter the  name of student "<<stud<<"\n";
		//cin.getline(nam,34);
		gets(nam);
		cout<<"Please enter your roll number for student "<<stud<<"\n";
        cin>>roll;
		cout<<"Please enter your marks  for student "<<stud<<" in ";
		for(int i=0; i<5; i++){
			cout<<"subject "<<i+1;
			cout<<endl;
			cin>>marks[i];

		}
	}

};
int main(){


	//cout<<"Hello World\n";

	ofstream of("file.txt");

	student s[5];

	cout<<"Please enter the data of the first five students\n";
	int loop=0;
	while(loop<5){
		s[loop].getData(loop+1);
		of.write((char*)&s[loop],sizeof(student));
		loop++;
	}

	of.close();

	cout<<"operation successfful\n";
	return 0;
}


yup, that is my code.
I am actually getting a very strange logical error..
It works fine till I get the first output. But then it kinda skips all the cin statements and executes abruptly to the next output, till the loop is completed. (Run it yourself, you will understand.)

Please help me, I am unable to figure out the problem
YOu have endline sitting in the input buffer when you calling gets second time, so it reads it and writes nothing into array.
You need to skip that getline using ignore on cin.
http://stackoverflow.com/questions/9419500/getlinecin-astring-receiving-input-without-another-enter
http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction

And mixing C and C++ stream operations is a bad habit.
warning: ‘char* gets(char*)’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
warning: the `gets' function is dangerous and should not be used.
don't use 'gets()'
Last edited on
Topic archived. No new replies allowed.