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

时间:2017-01-05 16:55:10

标签: c++ vector ifstream ofstream

我正在写一个大小为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出现,有人知道为什么吗?

1 个答案:

答案 0 :(得分:0)

我建议重新组织读取功能:

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

在互联网上搜索“stackoverflow c ++为什么eof in while is bad”。