Original Post
While trying to programm a simple binary i/o I've come to the following problem: I try to write a struct with C++ strings in it to a binary file. It works well, put when reading the data with fstream.read, I can't output the strings (all non-string members of the struct work well). I assume the strings lack of a legth limitation, as the cout of one of them displays me a bunch of my memory and the crashes the program. The code looks like this (maybe a problem with the formatString function?): I hope you can give me some hints.
#include <iostream>
#include <fstream>
#include <string>
#define H_EDITOR 15
#define H_TYPE 10
#define H_AUTHOR 15
#define H_NAME 15
#define H_TILESET 15
using namespace std;
struct lvlHeader
{
string editor;
string type;
string author;
string name;
int dimension;
string tileset;
// char start_x, start_y, start_h; // should be inserted in the editor
} header;
void formatString(string *target, int desiredLength)
{
int stringLength = target->length();
if (stringLength > desiredLength)
target->erase(desiredLength);
else if (stringLength < desiredLength)
{
for (int i = 0; i < (desiredLength - stringLength); i++)
*target += " ";
}
}
int main () {
string filename;
int choice;
cout << "CPDS-Edit header creator v1.00";
cout << "\nChoose a function";
cout << "\n 1. Create new level";
cout << "\n 2. Display level header \n\n";
cin >> choice;
if (choice == 1)
{
// read/set header data
header.editor = "CPDS-Edit v1.00";
formatString(&header.editor, H_EDITOR);
header.type = "CPDS-Iso;";
formatString(&header.type, H_TYPE);
// getline also reads in whitespaces, so it's used instead of cin
cout << "Please enter author name: "; fflush(stdin);
getline(cin, header.author);
formatString(&header.author, H_AUTHOR);
[..]
// save to binary
cout << "Please enter file name: ";
cin >> filename;
filename += ".lvl";
ofstream level (filename.c_str(),ios::binary);
level.write((char *)(&header), sizeof(lvlHeader));
level.close();
}
else if (choice == 2)
{
filename = "G:\\test.lvl";
ifstream level (filename.c_str(),ios::binary);
if (level.good())
{
level.read(reinterpret_cast<char *>(&header), sizeof(lvlHeader));
cout << header.dimension;
}
level.close();
}
cout << "\n\n";
system("PAUSE");
return 0;
}