标题:C++中怎么把结构体保存到文件中求解。
只看楼主
xcstyle
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-3-13
 问题点数:0 回复次数:0 
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();
}
搜索更多相关主题的帖子: void name include 联系人 通讯录 
2012-03-17 20:44



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-363491-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.595370 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved