C++中怎么把结构体保存到文件中求解。
#include <iostream>#include <fstream>
void type ();
void input ();
using namespace std;
struct frd
{
char name[10];
char sex;
char tel[13];
};
int main()
{
int ch;
int a = 1;
do
{
cout << "欢迎使用通讯录系统~" << endl;
cout << "请选择你想要的操作:" << endl;
cout << "按1:打印通讯录" << endl;
cout << "按2:录入联系人到通讯录" << endl;
cout << "按3:退出通讯录" << endl;
cin >> ch;
switch (ch)
{
case 1 :
type ();
break;
case 2 :
input ();
cin.ignore(100, '\n');
cout << "按任意键继续~";
cin.get();
break;
case 3 :
cout << "已经成功退出O(∩_∩)O哈哈~" << endl;
a = 0;
return 0;
default :
cout << "输入错误!";
return 0;
}
} while (a);
return 0;
}
void type ()
{
fstream in ( "fileFrd.txt" , ios::in );
if ( !in )
{
cerr << "打开文件失败!" << endl;
}
char ch;
while ( in >> ch )
{
cout << ch ;
}
cout << endl;
in.close();
cout << "已经成功打印出来O(∩_∩)O哈哈~" << endl;
}
void input ()
{
struct frd frd1;
fstream out ( "fileFrd.txt" , ios::out );
if ( !out )
{
cerr << "打开文件失败!" << endl;
}
cout << "请输入名字:";
cin >> frd1.name;
cout << endl;
int a = 1;
do
{
cout << "请输入性别:";
cin >> frd1.sex;
switch (frd1.sex)
{
case 'M' :
case 'm' :
a = 0;
break;
case 'F' :
case 'f' :
a = 0;
break;
default:
cout << "请输入M F或者m f" << endl;
cin.ignore(100, '\n');
cin.get();
break;
}
}while (!(frd1.sex == 'M' || frd1.sex == 'm' || frd1.sex == 'F' || frd1.sex == 'f' ));
cout << endl;
cout << "请输入手机号码:";
cin >> frd1.tel;
cout << endl;
struct frd *p;
p = &frd1;
out.write((char *)&p,sizeof(frd));
cout << "成功录入O(∩_∩)O哈哈~" << endl;
cout << "\n\n";
out.close();
}