const char *初值赋值以及文件读取
#include<iostream> #include<fstream> #include<string> #include<cstring> using namespace std; class Student { public: Student(string number="123", double score=0, const char *name="noname") { this->number = number; this->score = score; this->name = new char[strlen(name) + 1];//之前写的程序总是忘记开辟空间这一步 strcpy(this->name, name); } ~Student() { //cout<<"~Stu()...."<<endl; delete[] name; } friend istream &operator>>(istream & is, Student& dt) { is >> dt.number>>dt.name>>dt.score; return is; } friend ostream &operator<<(ostream & os, Student& dt) { os << dt.name << "\t" << dt.number << "\t" << dt.score << "\n"; return os; } private: char *name; string number; double score; }; int main() { Student st[5]; int i; for(i=0;i<5;i++) cin>>st[i]; ofstream fout("date.dat",ios::binary); for(i=0;i<5;i++) fout.write((char*)&st[i],sizeof(st[i])); fout.close( ); ifstream fin("date.dat",ios::binary); for(i=0;i<5;i++) fin.read((char*)&st[i],sizeof(st[i])); cout <<"姓名\t"<<"学号\t"<<"分数\n"; for(i=0;i<5;i++) cout <<st[i]; fin.close( ); getchar();getchar(); return 0; }
不一样的烟火