试图通过将游戏角色写入二进制文件来保存我的游戏。不幸的是,我的二进制文件正在写入该文件,就好像它是一个文本文件一样。
如果我只是实例化一个字符串并为该字符串调用保存函数,它会完美地写入二进制文件。但是,如果我从我的 CharacterSave 函数调用相同的函数——它只是将文件显示为文本文件而不是二进制文件。
调用层次结构
Character.Save() 调用字符串保存,写入二进制文件。
Character.Save() 调用 pouch(即 coinpouch)保存,写入二进制文件。
Character.Save()调用钱包(即背包)保存,调用动态数组保存,将元素个数写入二进制文件,调用药水保存方法,调用字符串保存方法.
编辑:解决了问题。我不知道怎么做,只是制作另一个 .dat 文件就解决了。
调用保存函数
//Create instance of binary file object
std::ofstream file("game.dat", std::ios::out | std::ios::binary);
//Check if file is open
if(file.is_open())
{
//Save character
myFavoriteCharacter.Save(file);
//Close the file
file.close();
}
else
std::cout << "\nFile did not open! " << std::endl;
字符保存功能
void Character::Save(std::ofstream & file)
{
mName.Save(file);
mPouch.Save(file);
mPurse.Save(file);
}
字符串保存函数
void String::Save(std::ofstream & file)
{
int tempLength = 0;
tempLength = this->getLength();
//Write the length of the string
file.write(reinterpret_cast<char *>(&tempLength), sizeof(int));
//Write the string
file.write(reinterpret_cast<char *>(this->mStr), tempLength + 1);
}
CoinPouch(即小袋)保存功能
void CoinPouch::Save(std::ofstream & file)
{
file.write(reinterpret_cast<char *>(&mPlatinum), sizeof(int));
file.write(reinterpret_cast<char *>(&mGold), sizeof(int));
file.write(reinterpret_cast<char *>(&mSilver), sizeof(int));
file.write(reinterpret_cast<char *>(&mCopper), sizeof(int));
}
DynamicArray 保存函数
void DynamicArray::Save(std::ofstream & file)
{
//Write the number of elements
file.write(reinterpret_cast <char *>(&mElements), sizeof(int));
//Save each element
for(int i = 0; i < mElements; i++)
mArray[i].Save(file);
}
药水保存功能
void Potion::Save(std::ofstream & file)
{
mName.Save(file);
mDescription.Save(file);
mPotency.Save(file);
mCost.Save(file);
}
最佳答案
强制 Visual Studio 2012 打开一个名为“game2.dat”的新文件,它起作用了。现在有我的二进制文件的十六进制转储,而不是它给我的普通文本文件。太奇怪了,我真的不明白为什么会这样,但确实如此。
感谢那些阅读/回复的人。
关于c++ - 试图写一个二进制文件,得到一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16257762/