您的位置:首页 > 编程语言 > C语言/C++

C++文件I/O 以对象写文件后,读出对象时出现乱码,不知道怎么解决,贴出代码如下.

2009-04-15 16:24 591 查看
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

class Student;
istream & operator >> (istream & is,Student& student);
ostream & operator << (ostream & os,Student &student);
bool writeStudent(vector<Student> & vt);
vector<Student> & readStudent(vector<Student> & vt);
void displayStudent(vector<Student> & vt);

class Student{
private:
string name;
string number;
int age;
public:
Student();
Student(string ,string,int);
friend istream & operator >> (istream & is,Student &student);
friend ostream & operator << (ostream & os,Student &student);
friend bool writeStudent(vector<Student> & vt);
friend vector<Student> & readStudent(vector<Student> & vt);
};

Student::Student()
{
this->age=0;
this->name=name;
this->number=number;

}

Student::Student(string name ,string number,int age){
this->age=age;
this->name=name;
this->number=number;
}

//重载>>操作符
istream & operator >> (istream &is,Student &student)
{
cout<<"请输入姓名、学号、年龄"<<endl;
is>>student.name>>student.number>>student.age;
return is;
}

//重载<<操作符
ostream & operator << (ostream & os,Student &student)
{
os<<student.name<<"/t"<<student.number<<"/t"<<student.age;
return os;
}

//添加学生
vector<Student> & addStudent(vector<Student> & vt)
{
cout<<"start adding"<<endl;
int flag=0;
while(flag!=1)
{
Student *m_stu=new Student;
cin>>*m_stu;
vt.push_back(*m_stu);
delete m_stu;
cout<<"继续添加吗,1代表结束添加,0代表继续添加,1 or 0 ?"<<endl;
cin>>flag;

}
return vt;
}

//向文件中写学生信息
bool writeStudent(vector<Student> & vt)
{
ofstream myFile;
myFile.open("info.txt",ios::out|ios::binary);
if(!myFile)
{
cout<<"open txt error"<<endl;
return false;
}

for(int i=0;i<vt.size();i++)
{
cout<<i<<":"<<vt[i].name<<vt[i].number<<endl;
myFile.write((char *)(&vt[i]),sizeof(Student));
}
myFile.close();
return true;
}

//从文件中读信息
vector<Student> & readStudent(vector<Student> & vt)
{
ifstream myFile;
myFile.open("info.txt",ios::in|ios::binary);
if(!myFile)
{
cout<<"open txt error"<<endl;
return vt;
}
while(myFile.peek()!=EOF)
{
cout<<"reading"<<endl;
Student *stu=new Student;
myFile.read((char *)stu,sizeof(Student));
vt.push_back(*stu);
delete stu;
}
myFile.close();
displayStudent(vt);
return vt;

}

//显示学生信息
void displayStudent(vector<Student> & vt)
{
cout<<"姓名"<<"/t"<<"学号"<<"/t"<<"年龄"<<endl;
vector<Student>::iterator it=vt.begin();
while(it!=vt.end())
{
cout<<*it<<endl;
it++;
}

}

void main()
{
vector<Student> stuV;
stuV=readStudent(stuV);
stuV=addStudent(stuV);
displayStudent(stuV);
if(writeStudent(stuV))
cout<<"写入成功"<<endl;
else
cout<<"写入失败"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐