【发布时间】:2013-03-28 11:34:27
【问题描述】:
我是 C++ 的初学者。我已经通过一个对象数组输入了变量的值(属于一个类)。现在我如何将它们写入文本文件列,如下所示?谢谢…………
SLNO NAME ADDRESS PHONE NO TYPE
1. ABC xyzagsgshsh 27438927 Mobile
2. QWE qwhjbbdh 78982338 Landline
这是我存储数据的代码。如何将其制作成内容如下的文本文件?
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class emp
{
string name,address,phone,type;
public:
void getdata();
}obj[5];
void emp::getdata()
{
cout<<"\nEnter the details:";
cout<<"\nName: ";cin>>name;
cout<<"Address:";
cin>>address;
cout<<"Phone number: "; cin>>phone;
cout<<"\nType of phone? (Landline/Mobile) :";
cin>>type;
}
int main()
{
ofstream ptr;
ptr.open("Phone.dat",ios::out);
cout<<"\nEnter the no.of.records: ";
int n,i;
cin>>n;
for(i=0;i<n;i++)
{
obj[i].getdata();
ptr.write((char*)&obj[i],sizeof(obj[i]));
}
return 0;
}
【问题讨论】:
-
如果您输入了这些值,那么您已经完成了困难的部分,所以我有点困惑为什么您会卡在输出上。您能否展示到目前为止您编写的代码,或者解释您遇到的问题。你的问题有点含糊。
-
从学习标准库的格式化输出功能开始。您可以在 this website 上找到所有关于它们的信息,或者在 google 上查找“C++ 格式化输出”。
-
@john:代码如上。如前所述,我需要将 Phone.dat 文件制作成文本文件。
-
@Razius 好吧,您不使用用于二进制数据的
write,只是ptr << obj[i].name << '' obj[i].address << '\n';等是一个开始。使用ptr就像使用cout一样。由于您已经知道如何使用cout,因此您已经知道如何写入文件。