我有一个包含多个文本字符串作为成员的对象。我想一次将此对象全部写入文件,而不是将每个字符串写入文件。我该怎么做?
最佳答案
您可以覆盖 operator>>
和 operator<<
读/写流。
示例 Entry struct
有一些值(value):
struct Entry2
{
string original;
string currency;
Entry2() {}
Entry2(string& in);
Entry2(string& original, string& currency)
: original(original), currency(currency)
{}
};
istream& operator>>(istream& is, Entry2& en);
ostream& operator<<(ostream& os, const Entry2& en);
实现:
using namespace std;
istream& operator>>(istream& is, Entry2& en)
{
is >> en.original;
is >> en.currency;
return is;
}
ostream& operator<<(ostream& os, const Entry2& en)
{
os << en.original << " " << en.currency;
return os;
}
然后你打开文件流,并为你调用的每个对象:
ifstream in(filename.c_str());
Entry2 e;
in >> e;
//if you want to use read:
//in.read(reinterpret_cast<const char*>(&e),sizeof(e));
in.close();
或输出:
Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();
或者如果你想使用流 read
和 write
那么你只需替换 operator
中的相关代码s 实现。
当变量在你的结构/类中是私有(private)的,那么你需要声明 operator
s 作为友元方法。
您可以实现任何您喜欢的格式/分隔符。当您的字符串包含空格时,请使用 getline() 接收字符串和流而不是 >>
因为operator>>
默认使用空格作为分隔符。取决于你的分隔符。
关于c++ - 如何在 C++ 中将对象写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376193/