Ofstream不向文本文件写入对象

Ofstream does not write object to a text file

本文关键字:对象 文件 文本 Ofstream      更新时间:2023-10-16

我使用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_phoneget_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;

}