【发布时间】:2020-08-18 21:45:23
【问题描述】:
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
【问题讨论】:
-
您没有检查读取是否有效。所以最后一次读取失败,您只是打印
a的随机内容,这恰好是最后一次读取之前对象中的内容。要验证这一点,请在阅读之前清除内容,看看会发生什么。仅在读取成功时修复打印。 -
附言。像这样读写字符串是有问题的(非常错误),因为对象 uname 和 pword 是具有构造函数和东西的对象。
标签: c++ file-handling