I/O流 4.1

/*1.从键盘输入10个学生信息(学生信息包括学号、姓名、性别、成绩)
存放在磁盘文件f1.dat中,然后把f1.dat中的数据复制到f2.dat文件中并在屏幕显示出学生数据;*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class student
{
private:
    int id;
    string name;
    string sex;
    int grade;
public:
    student(){};
    ~student(){};
    void setid()
    {
        cin  >> id;
    }

    void setname()
    {
        cin >> name;
    }

    void setsex()
    {
        cin >> sex;
    }

    void setgrade()
    {
        cin >> grade;
    }

    int getid()
    {
        return  id;
    }

    string getname()
    {
        return name;
    }

    string getsex()
    {
        return sex;
    }

    int getgrade()
    {
        return grade;
    }
};

int main()
{
    student a[2];
    student b;

    cout << "请输入两个学生的信息:" << endl;

    for(int i=0;i<2;i++)
    {
        cout << "学号:";
        a[i].setid();
        cout << endl;
        cout << "姓名:";
        a[i].setname();
        cout << endl;
        cout << "性别:";
        a[i].setsex();
        cout << endl;
        cout << "分数:";
        a[i].setgrade();
        cout <<  endl;
    }

    fstream f1("C:\\Users\\HP\\Desktop\\aha\\C++\\experiment4.1\\f1.dat",ios::out|ios::in|ios::binary);
    fstream f2("C:\\Users\\HP\\Desktop\\aha\\C++\\experiment4.1\\f2.dat",ios::out|ios::in|ios::binary);
    if(f1)
    {
        for(int i=0;i<2;i++)
        {
              f1.write((char *)&a[i],sizeof(a[i]));
        }
        f1.seekp(0,ios::beg);
    }
    else
    {
        cout << "f1 DISCONSTRUCT" <<endl;
    }
    if(f2)
    {
        for(int i=0;i<2;i++)
        {
            f1.read((char *)&b,sizeof(b));
            cout << "学号:" << b.getid() << " "<< "姓名:" << b.getname() << " " << "性别:"  << b.getsex() << " " <<"分数:" << b.getgrade() <<endl;
            f2.write((char *)&b,sizeof(b));
        }
        f1.close();
        f2.close();
    }
    else
    {
       cout << "f2 DISCONSTRUCT" << endl;
    }

    return 0;

}


猜你喜欢

转载自blog.csdn.net/qq_38053395/article/details/80154635
今日推荐