为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?

Why does the data written in a file using a class object in C++ get stored in a non-text format?

本文关键字:数据 文本 格式 文件 存储 C++ 为什么 对象      更新时间:2023-10-16

我正在使用c ++将数据写入文件。当我只使用一个变量从用户那里获取输入然后写入文件时,它只是存储在该文件中。我的意思是我可以通过用记事本打开文件来阅读我的输入。但是当我定义一个类并使用其对象将数据写入文件时,它以不可读的格式存储。我无法仅通过使用记事本打开文件来读取我的输入。但是,在这两种情况下,当我使用 c++ 读取文件然后显示它们时,它们都显示了我输入的内容。所以,我想问一下,为什么在使用类时数据以其他格式存储,而在使用简单变量时则不然。

使用正态变量:

#include <fstream>
#include <iostream>
using namespace std;
int main () {
//char data[100];
string data;
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin>>data;
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}

文件中的数据:

Ram
14

使用类:

#include <bits/stdc++.h>
using namespace std;
class person{
public:
int age;
string name;
int retAge(){
return age;
}
string retName(){
return name;
}
void takeInput(){
cout<<"nEnter Age: ";
cin>>age;
cout<<"nEnter Name: ";
cin>>name;
}
void show(){
cout<<"nAge: "<<age<<" and Name: "<<name;
}
};
int main(){
string filename = "someFile.dat";
ofstream outfile;
outfile.open (filename.c_str(), ios::app);
person p, q;
p.takeInput();
p.show();
outfile.write ((char *)(&p), sizeof(p));
outfile.close();
ifstream infile;
infile.open(filename.c_str());
infile.read((char*)&q, sizeof(q));
infile.close();
q.show();
return 0;
}

文件中的数据:

   ”Xã 

你正在写一个人的地址,投射到一个字符 *:outfile.write ((char *)(&p), sizeof(p));.它不会神奇地转换为显示对象所有内容的可读字符串;你需要自己做。

现在,这个人的地址是一个进入内存的指针,类似于0x42f1a5e2,这就是你在文件中写的内容。将其作为字符串读回会给您一些随机字符。

例如,年龄是一个int,因此您需要将其转换为字符串并写入该字符串,依此类推。

您的类包含 2 个字段:intstring;两者都不是文本,即使是后者(它本身包含与实现相关的字段)。这些数据类型的"<<"运算符知道如何将 转换为文本。

另一方面,您正在使用它来编写:outfile.write ((char *)(&p), sizeof(p));.这会将结构表示为字节流。这两个字段都将按原样写出,而不会转换为文本。write是一个低级函数,不执行也不能执行任何转换。

您真正需要做的是重载Person类中的"<<"运算符,告诉它您要如何打印字段。

相关文章: