为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?
Why does the data written in a file using a class object in C++ get stored in a non-text format?
我正在使用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 个字段:int
和string
;两者都不是文本,即使是后者(它本身包含与实现相关的字段)。这些数据类型的"<<"运算符知道如何将 转换为文本。
另一方面,您正在使用它来编写:outfile.write ((char *)(&p), sizeof(p));
.这会将结构表示为字节流。这两个字段都将按原样写出,而不会转换为文本。write
是一个低级函数,不执行也不能执行任何转换。
您真正需要做的是重载Person
类中的"<<"运算符,告诉它您要如何打印字段。
相关文章:
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中将十六进制字符串转换为文本数据
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 将文本文件解析为树状数据结构
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 如何读取文本文件中的数据并为每列 c++ 分配数组
- 在CRC-16 CCITT中将数据从二进制解码为文本,我应该输入一个码字,使用CRC生成器进行编码
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 模式匹配文本并提取C++中的数据
- C++将特定的数据模式从RFID阅读器写入文本文件
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 我无法将数据从数据网格列传输到 C# 中的数组以获取文本框建议收集数据
- 如何将函数的输出数据存储在文本文件中
- 将QDomDocument数据用作文本的更好方法
- 为什么使用 C++ 中的类对象写入文件中的数据以非文本格式存储?
- 在QT C++编辑Qtable模型数据时,我需要得到一个小盒子,我需要显示编辑文本,这怎么可能?
- 具有引用数据成员的结构不是文本类型吗?
- 如何在C 中编写一个程序,以说明不知道它正在阅读的数据文本文件中包含多少行
- 包括静态数据/文本文件