Issue
I'm doing some homework for a C++ class, I'm instructed to create a struct that holds data for 4 company divisions, and sales figures for each quarter. I'm to save the struct to a binary file then re-import it and read the data. Everything is actually running as expected, however after the output I get a RUN FAILED, exit code 1 error.
I initially thought it was due to an array out of bounds somewhere but looking back on the code I cannot find it.
* 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;
}
It outputs correctly, however tells me RUN FAILED exit code 1 after output.
Solution
Your struct division contains an std::string
, which is not a trivially-copyable type. An std::string
will generally contain pointers to dynamic memory allocations which are only valid for as long as the specific string object lives. You cannot simply write the bits that make up an std::string
object to disk, read it back into an std::string
object and expect to have a valid std::string
.
Answered By - Michael Kenzel