为什么函数写入文件c ++显示未知文本 [英] why function write in file c++ show unkown text

查看:198
本文介绍了为什么函数写入文件c ++显示未知文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#包括<&的iostream GT; 
#include< fstream>
#include< string>
using namespace std;

类XYZ
{
public:

string Name;
void Set()
{
cout<<输入字符串;
cin>>姓名;
}
};

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

Fil.write((char *)& ob,sizeof(ob)); //这个写入文本文件(ب|] helloجججججججججججج?)
Fil.close() ;

返回EXIT_SUCCESS;
}

解决方案

因为您编写XYZ类型的对象并使用XYZ实例的大小来确定如何要写的很多字节。



如果你只想写字符串Name,你需要得到指向数据的指针并指定字节数string(在这种情况下,字符串的长度)。





 Fil.write( ob.Name.c_str(),ob.Name.length()); 





问候,

伊恩。


#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;
}

解决方案

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.

Fil.write(ob.Name.c_str(), ob.Name.length());



Regards,
Ian.


这篇关于为什么函数写入文件c ++显示未知文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆