c++ - 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
解决方案
你不能合法地read
做write
任何你喜欢的事情。特别是,在您的情况下,读取或写入包含string
. 这样做会导致未定义的行为。
只有所谓的POD 类型才能以您尝试的方式读取或写入。
推荐阅读
- python - Pyinstaller可以使用其他文件夹中的数据执行吗?
- r - r 平均列表的元素
- java - 无法使用 Spring Batch 框架连接到 Oracle 数据源
- ruby-on-rails - 如何在更新之前拒绝 Rails 5 中的初始化嵌套关联?
- sql - 如何在postgres选择中获取第一次出现数字的位置
- javascript - 从具有多种场景的javascript中的字符串中删除子字符串
- ios - 对核心数据执行提取时间歇性崩溃
- mysql - SQL WHERE 子句逻辑不匹配
- jspdf - jspdf和autotables切割标题名称上的换行符
- swift - 如果我子类化一个类,我可以指定一个实例变量应该是某个子类吗?