c++ - 从文件读取时发生访问冲突 (C++)
问题描述
#include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
class Car {
private:
string carNm;
char carNum[20];
public:
void getCarData() {
cout << "car Name: ";
cin >> carNm;
cout << "car Number: ";
cin >> carNum;
cin.ignore();
}
void displayCarData() {
cout << "\nCar Name: " << carNm;
cout << "\nCar Number: " << carNum;
cout << "\n-----------------------------------------------\n";
}
int storeCar();
void viewAllCars();
};
int Car::storeCar() {
if (carNm == "" && carNum == "") {
cout << "car data not initialized";
return 0;
}
ofstream f;
f.open("car.txt", ios::out | ios::app);
f.write((char*)this, sizeof(*this));
f.close();
return 1;
}
void Car::viewAllCars() {
ifstream fin;
fin.open("car.txt", ios::in | ios::app);
if (!fin) {
cout << "File not found";
} else {
fin.seekg(0);
fin.read((char*)this, sizeof(*this));
while (!fin.eof()) {
displayCarData();
fin.read((char*)this, sizeof(*this));
}
fin.close();
}
}
int main() {
Car c;
c.getCarData();
c.storeCar();
c.viewAllCars();
system("PAUSE");
return 0;
}
错误消息:file2.exe 中 0x0fabad7a (msvcp100d.dll) 处的未处理异常:0xC0000005:加载位置 0x00214afc 时发生访问冲突。
什么可能导致此错误?将数据存储到文件中工作正常。但是,从文件中读取时会发生这种情况。我正在使用 Visual Studio 2010。
解决方案
推荐阅读
- c# - Unity:发布请求无法连接到目标主机
- excel - 在 lineChart excel 图中添加和查看 dataLabels (CTDLbls)
- teradata - Teradata:连续季度排名。
- python - 需要python中这个字符串的正则表达式吗?
- json - 可以/应该在带引号的json中传递布尔值吗?
- javascript - “in”运算符在 IE11 中无法按预期使用日期字符串
- javascript - 如何使用 httpPost() 函数从 p5.js JavaScript 库发布 xml 数据(例如 xml 文件)?
- java-8 - 如何转换列表
进入地图 > - python - Trouble to read an excel file with pandas
- rust - How to put heterogeneous types into a Rust structure