C++文件流问题
我正在用 C++ 制作一个简单的游戏,我希望将游戏结束时的最高分写入文本文件中。我使用 fstream 首先读取最后保存的高分并将其与新的高分进行比较。文本文件中的输出看起来像这样 (0НН),但事实并非如此。我对此感到非常沮丧。 这是我的代码的一部分。
double score_num=0;
fstream datafile("score.pon"); //Declaration of variables
...
if(SPEED>score_num)
{
score_num=SPEED;
}
//getting the score
...
datafile<<score_num; //Writing it to the file
I'm making a simple game in C++ and I want the highest score at the end of the game to be written in a text file. I'm using fstream to first read the last saved highscore and compare it to the new highscore. The output in the text file looks like this (0НН) and it shouldn't. I'm realy frustrated with this.
Here's a part of my code.
double score_num=0;
fstream datafile("score.pon"); //Declaration of variables
...
if(SPEED>score_num)
{
score_num=SPEED;
}
//getting the score
...
datafile<<score_num; //Writing it to the file
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用 ofstream 替换 fstream 效果非常好。也许您应该展示更多代码?另外,关闭文件是个好习惯:
我将把错误处理留给你
Replaced fstream by ofstream works like a charm. Perhaps you should show more code? Also, closing the file is good habit:
I'll leave errorhandling to you
Hacky 解决方案 - 作为 ifstream 打开文件,读取现有值,关闭它,调整分数,作为 ofstream 打开文件,写入分数,关闭它。或者,研究eekp() 函数的使用,并将分数写为二进制值,而不是文本。
Hacky solution - open the file as an ifstream, read existing value, close it, adjust score, open file as an ofstream, write score, close it. Alternatively, investigate the use of the seekp() function, and write the score as a binary value, not as text.
我对原始失败原因的最佳猜测是,当您从文件中读取最后一个字符时, EOF 位 已设置。在这种状态下,所有的read&写操作失败。您可以通过首先调用
clear
写入已到达末尾的文件流。但是,这并不能解决您的所有问题。如果您向文件写入的内容少于其当前长度(例如,旧的高分是“1.5”,新的高分是“2”),则部分旧数据仍将出现在文件末尾。只要分数永远不会有小数部分(在这种情况下,您可能应该使用整数类型,例如
unsigned long
),您就不会注意到该错误,因为b ⇒ len(a) ≤ len(b)。为了正确处理这个问题,您需要使用 unpersson 推荐的方法(这将截断文件或始终将相同数量的数据写入文件),或使用不同的 I/O 库(例如您平台的 C 库或boost),它提供了一种截断文件的方法(例如 POSIX
ftruncate< /代码>
)。
My best guess as to why the original was failing is that when you read the last character from a file, the EOF bit is set. In this state, all read & write operations fail. You can write to a file stream that's reached its end by calling
clear
first.However, this won't solve all your problems. If you write less to the file than its current length (e.g. the old high score was "1.5" and the new high score is "2"), part of the old data will still be present at the end of the file. As long as scores never have a fractional part (in which case you should probably be using an integer type, such as
unsigned long
), you won't notice the bug, since a < b ⇒ len(a) ≤ len(b). To handle this properly, you'll need to use unapersson's recommended approaches (which will either truncate the file or always write the same amount of data to the file), or use a different I/O library (such as your platform's C library or boost) which provide a way to truncate files (such as the POSIXftruncate
).