c ++我在读取二进制文件时得到重复的信息

c++ i get duplicated info when i read a binary file

我正在写一个大小为 3 的向量,当我读取时,我得到一个大小为 4 的向量,最后一个索引是索引 2 的副本。

这是我的代码。

void IOManager::WriteBin(const string &filename, vector<userRank> highScorers, int rank) {

    ofstream fsalida(filename, ios::out | ios::binary); 

    if (fsalida.is_open())
    {
        for (int i = 0; i < highScorers.size();i++) {
            fsalida.write(reinterpret_cast<char*>(&highScorers[i]), sizeof(highScorers[i]));

        }
        //highScorers.size() is 3
        fsalida.close();      

    }else cout << "Unable to open file for writing\n";
}

vector<userRank> IOManager::ReadBin(const string &filename) {

    ifstream fentrada(filename, ios::in | ios::binary); 

    if (fentrada.is_open())
    {

        vector<userRank>bestPlayers;

        for (int i = 0; fentrada.good(); i++) {
            userRank tempUser;
            fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
            bestPlayers.push_back(tempUser);

        }
        //bestPlayers.size() is 4!!!!!! Im losing my mind
        fentrada.close();

        return bestPlayers;

    }
    else cout << "Unable to open file for reading\n";   

}

这是我的 UserRank 结构

struct userRank
{
    char userName [5];
    int score;  
};

由于某种原因出现疯狂的 userRank,有人知道为什么吗?

我建议重组阅读功能:

userRank tempUser;
for (int i = 0;
     fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
     i++)
{
    bestPlayers.push_back(tempUser);
}

在互联网上搜索 "Whosebug c++ why eof in while is bad"。