#include <iostream> #include <vector> #include <stdio.h> using namespace std; class person{ public: person(string n = "noname", string num = "123"):name(n),number(num) {} void showPerson(); public: string name; string number; }; vector<person*> dataRead(vector<person*> & data) { FILE* fp = NULL; fp = fopen("data.txt","rb"); person* temp; if(fp == NULL) { cout << "error\n"; } int i = 0; while(fread(&data[i],sizeof(person),1,fp)) { temp = new person; data.push_back(temp); } fclose(fp); return data; } void dataWrite(vector<person*> & data) { FILE* fp = NULL; fp = fopen("data.txt","wb"); if(fp == NULL) { cout << "error\n"; } int n = data.size(); int i = 0; while(i < n) { fwrite(&data[i],sizeof(person),1,fp); i ++; } fclose(fp); } int main() { vector<person*> data; data = dataRead(data); string name; string number; while(1) { cout << "Input Name\n"; cin >> name; if(name == "#") break; cout << "Input number\n"; cin >> number; data.push_back(new person(name,number)); } int i = 0; for(i = 0; i < data.size(); i++) { data[i]->showPerson(); } dataWrite(data); for(i = 0; i<data.size(); i++) { delete data[i]; } }
用的是c语言的文件读取,C++的文件读取不会,读入vector的时候老段错误,麻烦给看下,vector里存入的是person*类型的,我类型跟指针方面有些不理解,并且vector不是很熟练,麻烦大神帮忙看下,顺便指出哪里的问题,感谢!
onemoo
慕九州2325515
相关分类