为什么在程序按预期运行和输出后出现运行失败错误?
Why do I get a run failed error after program runs and outputs as expected?
我正在为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
。
相关文章:
- Active Directory:从网络服务帐户下运行的Windows服务调用ADsOpenObject时失败
- 换位表导致测试失败(但在游戏中运行良好)
- 为什么 KMS drmModeSetCrtc() 在 X11 会话中运行时会失败并被拒绝权限?
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 如何让谷歌测试正常运行。测试总是失败。(它不会编译)
- 程序'main.exe'运行失败:指定的可执行文件不是此操作系统平台的有效应用程序
- 运行失败/分段故障binaryTree C
- 为什么在程序按预期运行和输出后出现运行失败错误?
- 在 Netbeans 8.2、c++ "No such file or directory"(初学者)中运行失败
- C++ 使用字符串时运行失败
- 运行失败,没有任何异常
- Qt 编译成功,但运行失败
- C++ 运行失败:退出值 2 - 我的代码出了什么问题?
- 在简单的c++程序上运行失败
- WxWidgets 应用程序运行失败
- 运行失败(退出值1)c++
- 从源代码构建GCC 5.4;这样构建的可执行文件试图链接不兼容的libstdc++,但运行失败
- 运行失败(exit value -1.073.740.940)
- c++构建成功,但运行失败
- 随机运行失败与简单的计数项目