以下定义操作一个Books类,并在main里面定义了一个类数组,要求用户输入ISBN(书号)和bookname(书名),将用户输入的信息保存到文件中,并进行读取操作。
结构体定义:
class Books{
public:
int ISBN;
char bookname[20];
Books(){}
Books(int ISBN_,char* bookname_)
{
ISBN=ISBN_;
strcpy(bookname,bookname_);
}
public:
//三个成员函数:
//put the value in the vector structs
void input(vector<Books> &s);
// the args means to use the vector declared in main() to write the msg to file
void savedata(vector<Books> &s);
// the args means to use the vector declared in main() to recieve the msg in the file
void readdata(vector<Books> &s);
};
主函数:
(主函数创建一个Books对象,用来调用成员函数,并创建vector 对象 ,用来保存多个类。
接着选择读或者写操作。)
//主函数运行:
#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>
#include<vector>
int main()
{
Books a;//an object to call the member function
vector<Books> arr_keep_books;// an array to keep the books structs
cout<<"0"<<" "<<"write"<<endl;
cout<<"1"<<" "<<"read"<<endl;
bool flag;
cin>>flag;
//press '0' to write,and press '1' to read
if(flag==false)//选择写到文件里或从文件中读取。
{
a.input(arr_keep_books);
a.savedata(arr_keep_books);
}
else
{
a.readdata(arr_keep_books);
}
return 0;
}
运行结果展示:
(1)将输入信息写入文件中:
(2)从文件中读取:
**成员函数细节:三个函数 1,输入 2,写入 3,读取 **
1.用户端输入信息:
void Books::input(vector<Books> &s)
{
int ISBN;
char bookname[20];
char author[20];
cout<<"Input ISBN "<<endl;
cin>>ISBN;
cout<<"Input bookname "<<endl;
cin>>bookname;
s.push_back(Books(ISBN,bookname));
}
2.将信息写入到文件中。(保存)
void Books::savedata(vector<Books> &s)
{
if(s.empty()==1){
cout<<"wrong"<<endl;
return;
}
FILE *fp=fopen("renewal2.txt","w");
fwrite(&s.back(),sizeof(Books),1,fp);
fclose(fp);
}
3.从文件中读取:
编程中遇到的bug提醒:要fread中的第一个参数要给它分配内存。所以文中在readdata 函数中要先用push_back()分配一个class 单元的内存。
void Books::readdata(vector<Books> &s)
{
FILE* fp2=fopen("renewal2.txt","r");
int nread;
s.push_back(Books());
//用默认构造函数位 vector<Books> s分配一个单元的内存,
for(int i=0;i<s.size();i++)
{
nread=fread(&s[i],sizeof(Books),1,fp2);
}
//显示读取的信息
for(int i=0;i<s.size();i++)
{
printf("%d\n",s[i].ISBN);
printf("%s\n",s[i].bookname);
}
fclose(fp2);
}