I'm new to C++ so I'm not fully used to the syntax yet. I do know more than the basics of C# syntax tho, which I have been using for the better part of a year now, and I have 2 years of PHP and python to go with that.
I'm tryng to write a struct with a vector inside of it to a file, and read it back at a different moment;
struct inventoryItem
{
std::string itemName;
bool unlocked{false};
};
struct saveData
{
std::string userName{"John"};
int hunger{100};
int health{100};
int money{5};
std::vector<inventoryItem> inventory;
};
I'm saving it to the file like so:
void saveGame::createSave()
{
saveData saveObj;
inventoryItem newItem;
newItem.itemName = "shoes";
newItem.unlocked = true;
saveObj.inventory.push_back(newItem);
newItem.itemName = "knife";
saveObj.inventory.push_back(newItem);
// std::thread saveThis(save, saveObj);
// saveThis.join();
save(saveObj);
return;
}
void saveGame::save(saveData toSave)
{
std::fstream fileW(saveGame::fileName, std::ios_base::in);
if (!fileW.good() || !fileW.is_open())
{
system("exit");
} else
{
fileW.write((char *) &toSave, sizeof(saveData));
fileW.close();
}
return;
}
and I retrieve it like so:
saveGame::saveData saveGame::getSave()
{
std::fstream fileR(saveGame::fileName, std::ios_base::out);
saveData toRetrieve;
if (!fileR.good() || !fileR.is_open())
system("exit");
else
{
fileR.read((char *) &toRetrieve, sizeof(saveData));
}
return toRetrieve;
}
saveGame::saveData data = saveObj.getSave();
std::cout<<data.userName<<std::endl;
std::cout<<data.health<<std::endl;
std::cout<<data.inventory[0].itemName; // I've also tried looping through the vector, but this also did not work. Even when I don't try to access it, it will crash after it has processed the other pieces of data
Now, everything works correctly. And I can access all the data, except for the vector struct that's inside of it. As soon as it gets to that piece of data, the program crashes without a single error code. I do, however get a windows message saying "a.exe has stopped working" but it does not produce a Debug message. If possible, could you use simple terms in the explanation? I haven't gotten to advanced C++ yet. Thanks in advance
I've tried looping through the vector, not accessing it at all, and simply printing the first piece of data from it.
I am expecting this:
*CONSOLE OUTPUT*
John //username
100 // health
shoes // inventory.itemName (string)
true // inventory.unlocked (bool)
knife // inventory.itemName (string)
false // inventory.unlocked (bool)
But I am instead getting
*CONSOLE OUTPUT*
John //username
100 // health
and... BAM "a.exe has stopped working" without a debug message