4.2 I/O 流

本文介绍了一个简单的图书管理程序设计,该程序使用C++实现,能够连续将新书信息存入文件,并支持根据书名进行搜索的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 设计一个管理图书的简单程序,提供的基本功能包括:
可连续将新书存入文件“book.dat”中,新书信息加入到文件的尾部;
也可以根据输入的书名进行查找;把文件“book.dat”中同书名的所有书显示出来。
为简单起见,描述一本书的信息包括:书号,书名,出版社和作者*/
#include<iostream>
#include<string>
#include<cstring>
#include<fstream>
using namespace std;
class book
{
    private: int  id;
             char  name[20] ;
             char  publish[20];
             char  zuozhe[20];
    public :
        book(){};
        ~book(){};
        void set_id(){
            cin>>id;
        }
        int  get_id()
        {
            return id;
        }
       void set_name(){
            cin>>name;;
        }
        string  get_name()
        {
            return  name;
        }
        void set_publish(){
           cin>>publish;
        }
        string  get_publish()
        {
            return publish;
        }
        void set_zuozhe(){
            cin>>zuozhe;
        }
        string  get_zuozhe()
        {
            return zuozhe;
        }
        void setbook();
        void searchbook();
};
void book::setbook()
{
    book b;
    fstream f1("D:\\C++\\123\\book4.dat",ios::out|ios::in|ios::binary|ios::app);
    cout<<"         *******输入书本的信息******* "<<endl;
    cout<<"书号";
    b.set_id();
     cout<<"名字";
    b.set_name();
     cout<<"出版社";
    b.set_publish();
     cout<<"作者";
    b.set_zuozhe();
    if(f1)
    {
        f1.write((char*)&b,sizeof(b));
    }
    else{
        cout<<"f1写入失败"<<endl;
    }
    f1.close();
}

void book::searchbook()
{
     book b;
     char b_name[20];
     int  flag=0;
     fstream  f1("D:\\C++\\123\\book4.dat",ios::in|ios::out|ios::binary);
     cout<<" 请输入要查询的名字";
     cin>>b_name;
   while(f1.read((char *)&b,sizeof(b)))
          {
              if(strcmp(b_name,b.get_name().c_str())==0)
            {
                flag=1;
        cout<<"id       "<<b.get_id()<<endl;
        cout<<"书名     "<<b.get_name()<<endl;
        cout<<"出版社   "<<b.get_publish()<<endl;
        cout<<"作者     "<<b.get_zuozhe()<<endl;
            }
        if(flag==0){
            cout<<"没有找到你要的书"<<endl;
        }
    }

    f1.close();
}
int main()
{
    book b;
    int a;
    while(1)
    {
        cout<<"                             *******管理图书系统***********"<<endl;
       cout<<"************添加图书请按1"<<endl;
       cout<<"************查询图书请按2"<<endl;
       cout<<"************程序结束请按3"<<endl;
       cin>>a;
       switch(a)
       {
        case 1:b.setbook();
        break;
        case 2:b.searchbook();
        break;
        case 3:
        return 0;
       }

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值