Problem with class.


Facing problem with class ,I call the getdata function and then the putdata function but the name that I enter in the first time is always printed again and again. Please help. Its very urgent.
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
int genid()
{

	int n,x=0;
	ifstream fin("MembMast.dat",ios::in|ios::binary);
	fin.seekg(0);
	while(fin.read((char*)&ob1,sizeof(ob1)))
	{
	}
	n=fin.tellg();
	if(n<=0)
		x=10001;
	else
	{
		x=ob1.retmemb()+1;
	}
	fin.close();
	return x;
}
class neww
{
	private:
		char name[20];
		int membno;
	public:
		void getdata()
		{
			cout<<"Enter your name : ";
			gets(name);
			membno=genid();
		}

		int retmemb()
		{
			return membno;
		}
		void putdata()
		{

			cout<<endl<<"Name : "<<name;
			cout<<endl<<"Membership Number : "<<membno;
		}
}ob1;
void newmem()
{
	int p,i=4,r;
	char str[15],ch;
	do
	{
                ob1.getdata();
	 	ob1.putdata();
		ofstream fout("MembMast.dat",ios::app,ios::binary);
		fout.write((char*)&ob1,sizeof(ob1));
		fout.close();
                cout<<"\n\nDo you want to enter more records?(y/n)";
		cin>>ch;
	}while(ch=='y')
A few problems:

Line 7, 15: reference ob1, but ob1 hasn't been seen yet by the compiler. This should not even compile.

Line 52: You're using , between ios::app and ios::binary. It should be |.

Line 29: gets copies up to to but not including the NL character. Therefore the NL character is left in the input buffer to be encountered and not removed by the next gets.

Use cin.ignore() to empty the buffer between reads.
http://www.cplusplus.com/reference/istream/istream/ignore/



Line 29: gets copies up to to but not including the NL character. Therefore the NL character is left in the input buffer to be encountered and not removed by the next gets.

No, the dangerous, depreciated C function gets() doesn't leave the new line in the stream, it removes then discards the new line character. However this function is so dangerous that it has actually been removed from the current C standard and should never ever be used. Mixing C-stdio functions with C++ streams should also be avoided whenever possible.

Topic archived. No new replies allowed.