Click here to Skip to main content
15,881,381 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include<iostream>
#include<fstream>
#include <string>
using namespace std;

class XYZ
{
public:

	string Name;
	void Set()
	{
		cout<<"Enter string";
		cin>>Name;
	}
};

int main ()
{
	ofstream Fil("Text.txt");
	XYZ ob;
	ob.Set();

	Fil.write((char *)& ob,sizeof(ob));//this write in text file (ب|] hello جججججججججج)
	Fil.close();
  
	return EXIT_SUCCESS;
}
Posted
Comments
Sergey Alexandrovich Kryukov 31-May-13 11:19am    
Why would you expect anything else? This is a normal result. If you write something which is not text (your structure has no text), you get something like this.
—SA
Anderso0on 31-May-13 11:21am    
ok , how i can fix this ??
Sergey Alexandrovich Kryukov 31-May-13 11:26am    
You should understand that such questions only make sense if you explain what do you want to achieve. Do you see the point?
—SA

1 solution

Because you writing the object of type XYZ and are using the size of an instance of XYZ to determine how many bytes to write.

If you just want to write the string "Name", you need to get the pointer to the data and specify the number of bytes in the string (in this case, the length of the string).

I.e.
C++
Fil.write(ob.Name.c_str(), ob.Name.length());


Regards,
Ian.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-May-13 11:25am    
The explanation is awkward, but it's hard to explain quickly, at the current OP's level. I, for example, did not even try. So, I voted 5.
—SA
Anderso0on 31-May-13 11:25am    
but if i have many field in class , must be write this statment to every field ??!!
CPallini 31-May-13 11:33am    
Yes. You might write a method (say 'write') of the XYZ class, accepting an const ofstream & as parameter for the purpose (you might also overload the insertion operator << see: http://msdn.microsoft.com/en-us/library/1z2f6c2k(v=vs.110).aspx )
Graham Breach 31-May-13 15:09pm    
I would vote +5 for this comment.
CPallini 31-May-13 15:40pm    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900