我正在使用 ifstream 和 ostream 来序列化我的数据,但我惊讶地发现“<<”运算符无法分隔两个相邻的字符串,而且分隔它们会非常复杂。
class Name
{
string first_name;
string last name;
friend std::ostream& operator<< (std::ostream& os, const Name& _name)
{
os << _name.first_name << _name.last_name;
return os;
}
friend std::istream& operator>> (std::istream& is, Name& _name)
{
is >> _name.first_name >> _name.last_name;
return is;
}
这不起作用,因为 << 和 >> 不写入空终止符,而 ifstream 读取变量 (first_name) 中的整个字符串,这有点令人失望。如何分别存储这两个字符串以便我也可以分别读取它们?我不明白<<
的动机是什么连接 ostream 中的所有字符串,这样我们就不能单独读回它们了!?
最佳答案
I don't understand what is the motivation of << concatenating all the strings in ostream so we can't read them back seperatly!?
这假设分开编写它们的唯一原因是将它们作为单独的字符串读取。考虑这样一种情况,某人有一对字符串,他们想将它们写入一个没有分隔符的流。或者一个字符串后跟一个他们不想要分隔符的 float 。
如果ostream
s 为每个 <<
自动插入分隔符输出,那么某人编写没有分隔符的文本会困难得多。他们必须手动将这些字符串和/或值连接成一个字符串,然后输出。
他们会用什么来连接?他们不能使用 ostringstream
就像你通常可能的那样,因为它使用与 ofstream
相同的设施.所以每个 <<
会在流中放置一个分隔符。
简而言之,IO 流 API 写入您告诉它要写入的内容,而不是您可能“想要”或可能不想写入的内容。它不是序列化 API; C++ 不是 C# 或 Java。如果您想要严肃的序列化功能,请使用 Boost.Serialization .
关于c++ - ifstream/ofstream真的是用来序列化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866626/