我正在使用 OpenGL 在 C++ 中编写游戏,但在使用文件流将分数导入文件并将其导出到要显示的程序时遇到了问题。
我有以下函数来导入和导出高分:(其中一些代码是我试图调试问题的)
void DisplayScores(void) // is going to be called by LoadHighScores()
{
glRasterPos2i(HighScore::x, HighScore::y);
printString(lineholder);
HighScore::y -= 15;
std::cout << "lineholder before being cleared: " << lineholder << std::endl;
lineholder = "";
}
void LoadScores(void) // Loads the high scores // called when the high scores option on the main menu has been selected
{
std::ifstream scorelist("scorelist.txt");
while (!scorelist.eof())
{
scorelist.get(getletter);
switch(getletter)
{
case '\n': DisplayScores(); break;
default: lineholder = lineholder + getletter; break;
}
}
scorelist.close();
}
void AddScore(char* name, int score) // takes arguments of the name of the player who has just played the game and their score is also passed and copied to the config file
{
std::ofstream addscore("scorelist.txt", std::ios::app);
addscore << name; // name of the player achieving the score
addscore << ":"; // if addscore.get() == ':' you know the score is going to come after this
addscore << score;
addscore << std::endl; // end the line in the text file so when you encounter '\n' you know you need to translate to a new line to display someone elses score
addscore.close();
}
以及以下使用这些函数的代码:(else 语句是主菜单分支的一部分,如果未选择“播放”则调用该分支)
else
{
// display the high scores here
std::cout << "in the else statement";
LoadScores();
AddScore("this", 20);
}
当我构建程序时,我只是得到“在 else 语句中”,但没有任何内容写入乐谱文件,并且 DisplayScores() 似乎也没有被调用。
文本文件仅包含以下内容:
Nick 10
Jason 50
最佳答案
一些注意事项:
while( !scorelist.eof() )
几乎不是您想要的。 istream::eof()
在第一次读取出错后设置,因此在循环开始时检查 istream::eof()
意味着进入循环,读取所有数据,然后进行处理。然后当到达 eof
时,设置标志而不是读取数据(在读取函数中)。然后完成所有处理(因为循环没有中止),最后看到标志。这通常会导致文件的最后一行被写入两次。
除此之外,您调用 LoadScores()
的代码已被注释掉。如果这是您使用的实际代码,那么这就是您的问题。如果它不是您使用的实际代码,请更新您的问题,我会再看看。
关于c++ - 使用filestream实现高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656908/