程序在尝试将 file.read() 文件() 到新变量时停止工作



好的,所以我有这段代码,我只想将我的结构写入文件,然后使用另一个变量读取,因为我想在读取时返回userRankings的向量。

这是我的写/读

void IOManager::WriteBin(const string &filename, userRank u1) {
    ofstream fsalida(filename, ios::out | ios::binary); //obrim un archiu per escriure en binari i de tipo append per poder escriure al final i no xafar-ho tot cada cop
    if (fsalida.is_open())
    {
        fsalida.write(reinterpret_cast<char*>(&u1), sizeof(u1));
        fsalida.close();

    }
    else cout << "Unable to open file for writingn";
}
void IOManager::ReadBin(const string &filename) {

    ifstream fentrada(filename, ios::in | ios::binary); //ate per posarnos al final del archiu i tenir el tamany
    if (fentrada.is_open())
    {   
        userRank tempUser;
        fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
        fentrada.close();
        cout << sizeof(tempUser) << endl;
    }
    else cout << "Unable to open file for readingn";   
}

和我的用户排名:

struct userRank
{
    std::string userName;
    int score;
};

失败的行是fentrada.read(reinterpret_cast(&tempUser),sizeof(tempUser));

请帮忙,这似乎适用于整数、字符等,但不适用于字符串和复杂类型,有人知道为什么吗?

以这种方式使用 reinterpret_cast 是危险的,并且可能由于多种原因而中断。 在这种特殊情况下,它不起作用的原因是struct userRank包含不是 POD 类型(普通旧数据类型)的std::string。这意味着你不能简单地设置它的位并期望获得正确的状态。 std::string包含指向已分配内存的指针。设置std::string的位不会分配它期望在该指针地址找到的内存。

快速解决方法(相对而言)是使用 std::array 而不是 std::string 来存储userName .正确的解决方法是编写函数,这些函数将逐个成员从文件成员中读取/写入结构的状态。

最新更新