为什么在程序按预期运行和输出后出现运行失败错误?

Why do I get a run failed error after program runs and outputs as expected?

本文关键字:运行 失败 错误 输出 程序 为什么      更新时间:2023-10-16

我正在为C++类做一些功课,我被指示创建一个结构,其中包含 4 个公司部门的数据和每个季度的销售数据。我将结构保存到二进制文件,然后重新导入并读取数据。一切实际上都按预期运行,但是在输出后我收到运行失败,退出代码 1 错误。

我最初认为这是由于某处的数组越界,但回顾代码我找不到它。

* Author: James Hartley
* Created on March 27, 2019, 10:09 PM
* Description: Gaddis Ch.12 Problem 11-12 Corporate Sales Data Output/Input
*/
#include <iostream>
#include <fstream>
using namespace std;
struct division {
string name;
int qtrSales[4];
};
void structToFile(string fileName, division* div, int arySize) {
fstream fileObject;
fileObject.open(fileName, ios::out | ios::binary);
fileObject.write(reinterpret_cast<char *>(div), sizeof(division) * arySize);
fileObject.close();
}
void fileToStruct(string fileName, division* div, int arySize) {
fstream fileObject;
fileObject.open(fileName, ios::in | ios::binary);
fileObject.read(reinterpret_cast<char *>(div), sizeof(division) * arySize);
fileObject.close();
}
int main(int argc, char** argv) {
division divs[4];
division divsImport[4];
divs[0].name = "East"; divs[1].name = "West"; divs[2].name = "North"; divs[3].name = "South";

for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << "Please enter Quarter " << j+1 << " sales for " << divs[i].name << " division" << endl;
cin >> divs[i].qtrSales[j];
}
}
structToFile("struct.dat", divs, 4);
fileToStruct("struct.dat", divsImport, 4);
for (int i = 0; i < 4; i++) {
cout << "Division: " << divsImport[i].name << endl;
for (int j = 0; j < 4; j++) {
cout << "Quarter: " << j+1 << endl;
cout << "Sales: " << divsImport[i].qtrSales[j] << endl;
}
}
return 0;
}

它正确输出,但是在输出后告诉我运行失败退出代码 1。

您的结构划分包含一个std::string,它不是一个普通可复制的类型。std::string通常包含指向动态内存分配的指针,这些指针仅在特定字符串对象存在期间有效。您不能简单地将构成std::string对象的位写入磁盘,将其读回std::string对象并期望具有有效的std::string