首页 > 解决方案 > 从文件读取时发生访问冲突 (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++visual-studio-2010

解决方案


推荐阅读