mercredi 31 août 2016

Data is not being written properly, while Writing an object to a file in c++

I have created 2 classes , One which creates the object and another which saves the object to a file.

The file is being created properly , but when i read the file directly from the location , it has junk values in it

Is it because iam type casting the object to char*, what should be the right way?

class custFile {
public :
 void append(myCust a)
 {
    myObj.open("/Users/tejas/Documents/cust.txt",std::ios::app);
    myObj.seekp(0,ios::end);
    myObj.write( (char *) &a ,  sizeof(myCust));
    myObj.close();
 }

} ;

class myCust {
public:
  void getdata(){
      std::cout<<"Enter Acno , CName,bal \n" ;
      std::cin>>acno>>cname>>bal;
  }
};

int main(int argc, const char * argv[]) {
  myCust custObj;
  custObj.getdata();
  custFile obj;
  obj.append(custObj);  
}

The Input is

123 Peter 10000

Below is the data in the file

{^@^@^@[Peter^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@~»F

PS: I have nt included the header files here Thanks

Aucun commentaire:

Enregistrer un commentaire