首页 > 解决方案 > read 方法从文件中返回最后一个对象两次

问题描述

read 方法两次返回最后一个对象。我尝试在读取行之前使用tellg,似乎最后一个对象本身在文件中写入了两次。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Abc
{
    string uname, pword;
public:
    void getdetails()
    {
        cout << "enter a password";
        getline(cin, pword);
        cout << "enter username";
        getline(cin, uname);
    }
    void printdetails()
    {
        cout << uname << " " << pword;
    }
};
int main()
{
    fstream f;
    int i, j;
    f.open("gamma.txt", ios::out | ios::binary | ios::app);
    Abc a;
    for (i = 0; i < 2; i++)
    {
        a.getdetails();
        f.write((char*) &a, sizeof(a));
    }
    f.close();
    f.open("gamma.txt", ios::in | ios::binary);
    for (i = 0; i < 2; i++)
    {
        f.read((char*) &a, sizeof(a));
        a.printdetails();
    }
    f.close();
}

这是输出。我没有得到两个对象,而是两次得到第二个对象。

enter a password
123
enter username
ralph
enter a password
321
enter username
john
john 321john 321

标签: c++file-handling

解决方案


你不能合法地readwrite任何你喜欢的事情。特别是,在您的情况下,读取或写入包含string. 这样做会导致未定义的行为。

只有所谓的POD 类型才能以您尝试的方式读取或写入。


推荐阅读