2015-11-13 58 views
0

所以我写了一个程序,我可以输入4个值的名字,姓氏,身高和签名。我将所有值存储在Vector中,但现在我想了解如何从矢量中获取值并将其存储在文件中,然后从文件中读取并存储回矢量中。C++读写结构对象到一个文件

vector<Data> dataVector; 
struct Data info; 
info.fname = "Testname"; 
info.lname = "Johnson"; 
info.signature = "test123"; 
info.height = 1.80; 
dataVector.push_back(info); 

代码看起来像这样我还没找到存储结构的对象到一个文件,所以我要求社区的一些帮助。

+1

为向量中的每个结构存储/加载成员。 – Unimportant

回答

2

你应该提供你的结构有一个方法将其写入流:

struct Data 
{ 
    // various things 
    void write_to(ostream& output) 
    { 
     output << fname << "\n"; 
     output << lname << "\n"; 
     // and others 
    } 
    void read_from(istream& input) 
    { 
     input >> info.fname; 
     input >> info.lname; 
     // and others 
    } 
}; 

或者提供两个独立的功能来完成这项工作,就像这样:

ostream& write(ostream& output, const Data& data) 
{ 
    //like above 
} 
// and also read 

或者,更好,超载<<>>操作:

ostream& operator<<(const Data& data) 
{ 
    //like above 
} 
// you also have to overload >> 

或者,甚至更好,使用提供这种功能的现有库,如Boost。

最后一个选项有许多优点:您不必考虑如何分离文件中结构的字段,如何在同一个文件中保存更多实例,在重构或修改时必须减少工作量结构。