c++ - 使用filestream实现高分

标签 c++ filestream

我正在使用 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/

相关文章:

php - 使用 php 加载和读取 csv 文件

C# 将 MemoryStream 转换为 FileStream

sql-server - 文件流与本地保存在sql server中?

c++ - 如何在 MFC 中向 CMenu 添加子菜单?

c++ - 是否可以将html和js嵌入到QwebKit中

c++ - std::queue 具有不同的容器类型,具体取决于运行时数据

C++ 类引用

c++ - 如何使碰撞仅影响 lib Bullet 中 X 和 Z 轴上的旋转?

image - 是否有可用于将数据从 "Image"列迁移到 "FileStream"列的 SQL 查询?

c# - Binaryreader 从分块加载的 Filestream 中读取