如何在C ++中将对象写入文件 [英] How to write an object to file in C++

查看:281
本文介绍了如何在C ++中将对象写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象与几个文本字符串作为成员。我想立即将这个对象写入文件,而不是将每个字符串写入文件。

解决方案

您可以覆写 operator>>



示例 code>带有某些值的条目结构

  struct Entry2 
{
string original;
string currency;

Entry2(){}
Entry2(string& in);
Entry2(string& original,string& currency)
:原始(原始),货币
{}
}


istream& operator>>(istream& is,Entry2& en);
ostream& operator<<(ostream& os,const Entry2& en);实施:

  

code> using namespace std;

istream& operator>>>(istream& is,Entry2& en)
{
是>原始
是>> en.currency;
return is;
}

ostream& operator<<<(ostream& os,const Entry2& en)
{
os< en.original< < en.currency;
return os;
}

然后你打开filestream,并为每个对象调用:

  ifstream in(filename.c_str()); 
Entry2 e;
在>> e;
//如果你想使用read:
//in.read(reinterpret_cast<const char *>(& e),sizeof(e));
in.close();

或输出:

  Entry2 e; 
//在e
中设置值outstream out(filename.c_str());
out<< e;
out.close();

或者如果要使用流,那么您只需替换运算符的相关代码。



当变量在你的struct /类中是private时,你需要声明 operator 作为朋友方法。



您可以实施任何您喜欢的格式/分隔符。当你的字符串包含空格时,使用getline()接受一个字符串和流而不是>> ,因为 operator>> 默认使用空格作为分隔符。取决于您的分隔符。


I have an object with several text strings as members. I want to write this object to the file all at once, instead of writing each string to file. How can I do that?

解决方案

You can override operator>> and operator<< to read/write to stream.

Example Entry struct with some values:

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);

Implementation:

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;
}

Then you open filestream, and for each object you call:

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();

Or output:

Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();

Or if you want to use stream read and write then you just replace relevant code in operators implementation.

When the variables are private inside your struct/class then you need to declare operators as friend methods.

You implement any format/separators that you like. When your string include spaces use getline() that takes a string and stream instead of >> because operator>> uses spaces as delimiters by default. Depends on your separators.

这篇关于如何在C ++中将对象写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆