Why do we use write function twice ?
Aug 26, 2014 at 6:59pm UTC
Why do we need to use read function in while loop when already used once before starting the loop ? And whats the exact use of getting the size of class ?
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>
#include "stdafx.h"
#include <iostream>
using namespace std;
class student
{
private :
int reg;
char name[20];
public :
void setreg()
{
cout<<"enter reg" ;
cin>>reg;
}
void setname()
{
cout<<"eneter name" ;
cin>>name;
}
int getreg()
{
return reg;
}
char *getname()
{
return name;
}
};
void main()
{
ofstream Sfil("stud.dat" );
char ch;
student Svar;
while (1)
{
cout<<"want to enter more records" ;
cin>>ch;
if (ch=='n' )
break ;
Svar.setreg();
Svar.setname();
Sfil.write((char *)&Svar,sizeof (student));
}
Sfil.close();
cout<<"do u wanna cont ?" ;
cin>>ch;
if (ch=='y' )
{
ifstream Sfil("stud.dat" )
Sfil.read((char *)&Svar, sizeof (student));
while (Sfil)
{
cout<<"reg no. is" <<Svar.getnum();
cout<<"name is" <<Svar.getname();
Sfil.read((char *)&Svar, sizeof (student));
}
}
}
Aug 26, 2014 at 7:13pm UTC
Why do we need to use read function in while loop when already used once before starting the loop ?
Because you didn't use do ... while.
And whats the exact use of getting the size of class ?
Because "std::ofstream.write()" requires it as a parameter:
http://www.cplusplus.com/reference/ostream/ostream/write/
Aug 26, 2014 at 9:11pm UTC
You could just do
1 2 3 4
while (Sfil.read((char *)&Svar, sizeof (student))) {
cout<<"reg no. is" <<Svar.getnum();
cout<<"name is" <<Svar.getname();
}
Sfil.read()
returns a reference to Sfil
Topic archived. No new replies allowed.