C++ 从文件读取时发生读取访问冲突
我正在尝试读取Person.txt文件,该文件已写入Person对象。我收到以下错误:引发异常:读取访问冲突。 _Pnext是0x87E504 我试过调试,它执行的函数很好。它仅在函数完成后弹出错误 以下是我从文件中读取的代码:C++ 从文件读取时发生读取访问冲突,c++,file,class,C++,File,Class,我正在尝试读取Person.txt文件,该文件已写入Person对象。我收到以下错误:引发异常:读取访问冲突。 _Pnext是0x87E504 我试过调试,它执行的函数很好。它仅在函数完成后弹出错误 以下是我从文件中读取的代码: void readFromFile() { ifstream inFile("Person.txt", ios::in); Person p2; inFile.read(reinterpret_cast<char*>(&p
void readFromFile()
{
ifstream inFile("Person.txt", ios::in);
Person p2;
inFile.read(reinterpret_cast<char*>(&p2), sizeof(Person));
cout << "First Name: " << p2.getFirst() << endl
<< "Last Name: " << p2.getlast() << endl
<< "Gender: " << p2.getgender() << endl
<< "Age: " << p2.getAge() << endl;
}
人员类别:
Class Person {
public:
Person()
{
firstName = "N/A";
lastName = "N/A";
gender = "N/A";
age = 0;
}
Person(std::string first, std::string last, std::string gender, int age)
{
firstName = first;
lastName = last;
this->gender = gender;
this->age = age;
}
~Person()
{
std::cout << "Person Destructor" << std::endl;
}
void setFirst(std::string first)
{
firstName = first;
}
std::string getFirst() const
{
return firstName;
}
void setLast(std::string last)
{
lastName = last;
}
std::string getlast() const
{
return lastName;
}
void setGender(std::string gender)
{
this->gender = gender;
}
std::string getgender() const
{
return gender;
}
void setAge(int age)
{
this-> age = age;
}
int getAge() const
{
return age;
}
private:
std::string firstName;
std::string lastName;
std::string gender;
int age;
};
Person类具有std::string成员,其中包含指向存储在内存中其他位置的动态分配数据的指针。因此,您将无法以您尝试的方式使用ofstream::write和ifstream::read来写/读Person对象。您将只写入/读取指针值,而不是指向的实际字符数据。您必须逐个序列化数据成员。例如,在本例中,您可以简单地将每个字符串写入文本文件中自己的行,例如:
void writeToFile()
{
ofstream outFile("Person.txt");
Person p2("Joe", "Smoe", "M", 25);
//outFile.write(reinterpret_cast<char*>(&p2), sizeof(Person));
outFile << p2.getFirst() << "\n"
<< p2.getlast() << "\n"
<< p2.getgender() << "\n"
<< p2.getAge() << "\n";
}
void readFromFile()
{
ifstream inFile("Person.txt");
Person p2;
string s;
int i;
//inFile.read(reinterpret_cast<char*>(&p2), sizeof(Person));
getline(inFile, s);
p2.setFirst(s);
getline(inFile, s);
p2.setLast(s);
getline(inFile, s);
p2.setGender(s);
inFile >> i;
inFile.ignore(numeric_limits<streamsize>::max(), '\n');
p2.setAge(i);
cout << "First Name: " << p2.getFirst() << endl
<< "Last Name: " << p2.getlast() << endl
<< "Gender: " << p2.getgender() << endl
<< "Age: " << p2.getAge() << endl;
}
然后你可以这样做:
无效写入文件
{
ofstream outFilePerson.txt;
乔伊,斯莫,男,25岁;
输出文件>p2;
Person声明实际上是什么样子的?我怀疑它包含指向动态分配数据的指针,例如std::string数据成员的内部。如果是这样,那么您将无法按原样写入/读取Person对象,您将需要逐个序列化成员。我对其进行了编辑以显示Person类!有吗当你重新解释你的代码时,你知道你的代码是错的。在这种情况下,完全错了。@Adamwints这很奇怪,因为我遵循我的教科书,他们就是这么做的。-所以,最后,我脑海中多年的谜团可能会被解开。你不是唯一一个以这种方式编写代码的人,我一直想知道是谁在写代码是什么教这个方法?有成千上万的问题用同样的问题来标记C++,这个错误的技术不可能只是由不谨慎的语言学习者随机地捡到的。RemyLebeau真的是这样吗?你能保证性别和年龄之间的填充不会随着编译标志的变化而改变吗?er版本或其他东西?你能保证age的字节表示不会随着CPU版本、操作系统版本或其他东西的变化而变化吗?它可能有效,但也可能无效,在书中教人们以这种方式编码是鲁莽的。