Ofstream不向文本文件写入对象
Ofstream does not write object to a text file
我使用ofstream
使用dev c++将联系人管理器的对象写入文本文件。我的目标是将对象保存到文本文件中,以便也可以从文本文件中读取Name和Phone。下面是我的简单代码:
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
class phone
{
int phone;
string name;
public:void get()
{
cin>>phone;
cin>>name;
}
public:void show()
{
cout<<phone<<"-"<<name;
}
};
int main () {
phone p;
p.get();
p.show();
ofstream outfile("12.txt"); // Open the file in output mode
outfile.write((char*)&p, sizeof(p)); // Write the object into the file
return 0;
}
但是当我打开文本文件时,它显示了一些中文字符。有什么帮助,如何解决它?
写入对象是写入对象的二进制表示形式,而不是将成员转换为文本。用途:
outfile << p.phone << "-" << p.name << endl;
但是你需要将这些成员声明为public才能正常工作。或者您可以定义访问它们的公共get_phone
和get_name
函数,并在这里使用它们。
您还可以为您的类重载operator<<
,请参阅这里的示例来了解如何这样做。那么你就可以这样写:
outfile << p;
您正在混合二进制和文本格式。您编写一个二进制文件,然后尝试将其当作文本来读,而文本阅读器将二进制数据解释为奇怪的字符。我建议您坚持文本,并修改您的show()
,以允许它写入文件:
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
class phone
{
int phone;
string name;
public:
void get()
{
cin>>phone;
cin>>name;
}
void show(ostream &ostr)
{
ostr << phone << "-" << name;
}
};
int main ()
{
phone p;
p.get();
p.show(cout);
ofstream outfile("12.txt"); // Open the file in output mode
p.show(outfile);
return 0;
}
进一步的细化是可能的,一旦你有这个工作。
我重新安排你的代码,但我已经改变了大部分。希望我的解决方案能帮到你。
struct phone
{
int电话;
字符串名称;
};Int main () {
ofstream outfile("12.txt", ios::out); // Open the file in output mode
phone p[1];
cout<<"enter phone first"<<endl;
cin>>p[0].phone;
cin>>p[0].name;
outfile<<p[0].phone<<" - "<<p[0].name<<endl; // Write the object into the file
cout<<p[0].phone<<" - "<<p[0].name<<endl;
outfile.close();
cin.get();
return 0;
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在h文件中包含.o对象文件
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 从对象文件(.o)在macos上制作归档文件(.a文件)
- 检测 COFF 对象文件中C++内联符号
- 特定对象文件的单线程生成
- 使用对象文件读取三角形数据网格
- 链接时,不同静态库中的同一对象文件
- 防止临时对象文件访问 MSVC 中的磁盘
- 对在不同二进制文件中创建的对象文件的依赖关系
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 是否有正确的方法对生成文件中的对象文件使用模板命令?(C++)
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 使用 make 将对象文件放在特定目录中
- 如何从 3d 对象文件中获取 3d 坐标
- 为什么我的生成文件没有生成对象文件?
- 如何在OSX上正确创建C++对象文件(.o)
- sf::Windows上的音乐:api-ms-win-crt-locale-l1-1-0.dll:无法打开共享对象文件
- 使用nvcc(CUDA-RINSIDE)正确链接对象文件
- 链接节点本机模块中的提升库,对象文件需要替代库版本