在cpp中将对象写入文件 [英] writing an object to a file in cpp
问题描述
我正在尝试将对象的内容写入文件.这是我的代码
I am trying to write the contents of an object into a file. This is my code
void Write_data_intoFile(Customer c1)
{
ofstream fout("cust_details.txt", ios::out | ios::app);
fout.write(reinterpret_cast<char*> (&c1),sizeof c1);
fout.close();
}
这就是我调用该函数的方式
This is how i call the function
c[ Customer_count ].Write_data_intoFile(c[ Customer_count ]);
程序运行正常,但是内容未写入文件中.它显示红色标记,表示无法打开文件.如何解决这个问题
The program works fine, but the contents are not written in the file. It shows a red colour mark saying it cannot open the file. How to solve this
class Customer
{
char name[25];
int id;
}
我是通过以下方式全局创建对象的:
I created the objects, globally, by
Customer c[20];
我正在尝试以文本格式编写
I am trying to write it in a text format
推荐答案
好,首先您需要为Customer的文本I/O编写一个函数.传统上,该功能称为运算符<<.所以你需要像这样的东西
OK, first you need to write a function for text I/O of Customer. Traditionally that function is called operator<<. So you need something like this
ostream& operator<<(ostream& out, const Customer& c)
{
return out << c.name << ' ' << c.id << '\n';
}
也许(很难确定)您需要将该函数声明为Customer类的朋友,如果您遇到有关访问或私有的错误,则可能需要添加此行
Maybe (it's hard to be sure) you need to declare this function as a friend of your Customer class, if you get errors about access or private then you probably need to add this line
friend ostream& operator<<(ostream& out, const Customer& c);
在客户类中.
然后,您需要像这样从其他函数内部调用此函数
Then you need to call this function from inside your other function, like this
void Write_data_intoFile(Customer c1)
{
ofstream fout("cust_details.txt", ios::out | ios::app);
fout << c1;
fout.close();
}
那么您真的需要阅读一本关于C ++的好书,否则很难正确地理解这些东西.再次发布任何问题.
Then you really need to read a good book on C++, it's hard to get this stuff right otherwise. Any problems post again.
这篇关于在cpp中将对象写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!