這裡以一個簡單的學生信息管理系統為例。 首先是對象的建立,包括姓名,學號,成績,學分,等 如下: 這裡面包括兩個子對象, 復制代碼 1 class Student 2 { 3 public: 4 Student() :score(), birthday(){}//對子對象進行初始化 5 ~Student(){} 6 void InputInfo(); 7 void OutPutInfo(); 8 void ShowInfo(); 9 bool CreditManage(); 10 11 char *getNum(){ return num; } 12 char *getName(){ return name; } 13 bool getSex(){ return sex; } 14 float GetCredit(){ return credit; } 15 void swapStudent(Student &stu); 16 private: 17 char num[10]; 18 char name[20]; 19 bool sex; 20 Score score;//子對象 21 Birthday birthday;//子對象 22 float credit; 23 bool isChanged; 24 }; 復制代碼 然後主要還是文件讀寫。文件讀寫包括三個類,其中ifstream和ofstrean從fstream派生而來,可以在創建對象的時候直接初始化,這樣比較方便。也可以使用open函數打開文件 (1) ifstream類,它是從istream類派生的。用來支持從磁盤文件的輸入。 (2) ofstream類,它是從ostream類派生的。用來支持向磁盤文件的輸出。 (3) fstream類,它是從iostream類派生的。用來支持對磁盤文件的輸入輸出。 其中的文件讀寫的關鍵函數是read和write,這兩個函數可以讀寫固定長度的數據 istream& read(char *buffer,int len); ostream& write(const char * buffer,int len); 文件操作完畢一定要關閉文件,只需調用close()就行。 如file.close(); 定義一個全局函數用於獲取文件中對象的個數, 復制代碼 1 int GetNumberFromFile() 2 { 3 int count = 0;//對象個數,即學生人數 4 fstream infile("e:\\student.txt",ios::in | ios::binary);//以讀方式打開文件 5 if (!infile) 6 { 7 cout<<"open file error!"<<endl; 8 getchar(); 9 exit(0); 10 } 11 Student stu; 12 while (infile.read((char*)&stu,sizeof(stu)))//強制類型轉換為(char*), 13 { 14 count++; 15 } 16 infile.close(); 17 return count; 18 } 復制代碼 這裡的文件讀寫關鍵是在read函數,read函數會讀取數據一直到文件結束 1 basic_istream<Elem, Tr>& read( 2 char_type *_Str, //這裡是要保存的對象數組的地址 3 streamsize _Count//這裡是對象的大小 4 ); 因為數據是以二進制保存到文件中的,所以我們不用關心數據的格式,我們知道怎麼讀取數據就行了。向文件中寫入整個對象的好處是將來可以整個讀取出來進行操作,不必去考慮細節。 寫入文件和這個類似 復制代碼 1 Student stu1; 2 stu1.InputInfo(); 3 fstream outfile("e:\\student.txt", ios::app | ios::binary);//這裡以app方式打開文件進行添加 4 if (!outfile) 5 { 6 cerr << "open file error!"; 7 } 8 outfile.write((char*)&stu1, sizeof(stu1)); 9 outfile.close(); 復制代碼 以app方式打開文件進行添加,文件內部的位置指針會自動移動移動到文件末尾,直接添加文件到最後。 當對文件進行輸出時 復制代碼 1 fstream infile("e:\\student.txt",ios::in | ios::binary); 2 if (!infile) 3 { 4 cout<<"open file error!"<<endl; 5 getchar(); 6 //exit(0); 7 } 8 int len = 0; 9 len = GetNumberFromFile(); 10 if (len == 0) 11 { 12 cout << "no data!" << endl; 13 ch = '0'; 14 break; 15 } 16 Student *stu = new Student[len];//動態申請地址,因為這個數組大小是在運行過程中才能知道的 17 cout << "number\tname\tsex\tyear-month-day\tcredit" << endl; 18 for (int i = 0; i < len;i++) 19 { 20 infile.read((char*)&stu[i], sizeof(stu[i])); 21 stu[i].OutPutInfo(); 22 } 23 delete []stu; 24 infile.close(); 復制代碼 還有一些排序的簡單實現在下面的代碼中 整個程序代碼在這裡 復制代碼 1 #include <iostream> 2 #include "string" 3 using namespace std; 4 5 class Student; 6 bool SortByCondition(Student stu[],const int &len,const char &conditon);//排序 7 void SaveToFile(Student stu[],int num); 8 void ReadFromFile(Student stu[],int num); 9 int GetNumberFromFile(); 10 char Menu(); 11 char SortMenu(); 12 13 class Score 14 { 15 public: 16 Score(){ english = 0, math = 0; computer = 0; } 17 Score(float eng, float mat, float com) :english(eng), math(mat), computer(com){} 18 void InputScore() 19 { 20 cout << "enter english score:"; 21 cin>> english; 22 cout << "enter math score:"; 23 cin >> math; 24 cout << "enter computer score:"; 25 cin >> computer; 26 } 27 void outputScore() 28 { 29 cout << english << "\t" << math << "\t" << computer << "\t"; 30 } 31 float ScoreSum() 32 { 33 return (math + english + computer); 34 } 35 void swapScore(Score &scor)//對象交換數據 36 { 37 float ftmp = english; 38 english = scor.english; 39 scor.english = ftmp; 40 41 ftmp = math; 42 math = scor.math; 43 scor.math = ftmp; 44 45 ftmp = computer; 46 computer = scor.computer; 47 scor.computer = ftmp; 48 } 49 private: 50 float english; 51 float math; 52 float computer; 53 }; 54 55 class Birthday 56 { 57 public: 58 Birthday(){ year = 0; month = 0; day = 0; } 59 Birthday(int ye, int mon, int da) :year(ye), month(mon), day(da){} 60 void inputBirthday() 61 { 62 cout << "enter birthday like \"2014 05 01\":" << endl; 63 cin >> year >> month >> day; 64 } 65 void outputBirthday() 66 { 67 cout << year << "\-" << month << "\-" << day << "\t"; 68 } 69 void swapBirthday(Birthday &bir)//對象交換數據 70 { 71 int itmp = year; 72 year = bir.year; 73 bir.year = itmp; 74 75 itmp = month; 76 month = bir.month; 77 bir.month = itmp; 78 79 itmp = day; 80 day = bir.day; 81 bir.day = itmp; 82 } 83 private: 84 int year; 85 int month; 86 int day; 87 }; 88 89 90 class Student 91 { 92 public: 93 Student() :score(), birthday(){} 94 ~Student(){} 95 void InputInfo(); 96 void OutPutInfo(); 97 void ShowInfo(); 98 bool CreditManage(); 99 100 char *getNum(){ return num; } 101 char *getName(){ return name; } 102 bool getSex(){ return sex; } 103 float GetCredit(){ return credit; } 104 void swapStudent(Student &stu);//對象交換數據 105 private: 106 char num[10]; 107 char name[20]; 108 bool sex; 109 Score score; 110 Birthday birthday; 111 float credit; 112 bool isChanged; 113 }; 復制代碼 復制代碼 1 #include "student.h" 2 #include "iostream" 3 #include "fstream" 4 using namespace std; 5 6 7 void Student::InputInfo() 8 { 9 cout << "enter number(字符串)"; 10 cin >> num; 11 cout << "enter name(字符串)"; 12 cin >> name; 13 cout << "enter sex(0表示女,1表示男)"; 14 cin >> sex; 15 score.InputScore(); 16 birthday.inputBirthday(); 17 credit = score.ScoreSum() / 10;//計算得出學分 18 } 19 20 void Student::OutPutInfo() 21 { 22 cout << num << "\t" << name << "\t" << sex << "\t"; 23 //score.outputScore(); 24 birthday.outputBirthday(); 25 cout << credit << endl; 26 } 27 28 char Menu() 29 { 30 //system("cls"); 31 cout << "******************************************" << endl; 32 cout << "***welcome to student management system***" << endl; 33 cout << "******************************************" << endl; 34 cout << "please choose the number below:" << endl; 35 cout << "1--成績錄入" << endl; 36 cout << "2--成績顯示" << endl; 37 cout << "3--排序管理" << endl; 38 cout << "4--學分管理" << endl; 39 cout << "0--退出" << endl; 40 char ch = getchar(); 41 return ch; 42 } 43 44 void Student::swapStudent(Student &stu) 45 { 46 char tmp[10]; 47 strcpy_s(tmp, num); 48 strcpy_s(num, stu.num); 49 strcpy_s(stu.num, tmp); 50 51 char nam[20]; 52 strcpy_s(nam, name); 53 strcpy_s(name, stu.name); 54 strcpy_s(stu.name, nam); 55 56 bool btmp = sex; 57 sex = stu.sex; 58 stu.sex = btmp; 59 60 score.swapScore(stu.score); 61 birthday.swapBirthday(stu.birthday); 62 63 float ftmp = credit; 64 credit = stu.credit; 65 stu.credit = ftmp; 66 67 btmp = isChanged; 68 isChanged = stu.isChanged; 69 stu.isChanged = btmp; 70 71 } 72 73 char SortMenu() 74 { 75 cout << "選擇要進行排序的方式:"; 76 cout << "1--學號" << endl; 77 cout << "2--姓名" << endl; 78 cout << "3--性別" << endl; 79 cout << "4--學分" << endl; 80 cout << "5--返回上一級" << endl; 81 getchar(); 82 char ch = getchar(); 83 return ch; 84 } 85 86 bool SortByCondition(Student stu[], const int &len, const char &conditon)//排序 87 { 88 char tmp = conditon; 89 int length = len; 90 switch (tmp) 91 { 92 case '1'://學號 93 { 94 for (int i = 0; i < length; i++) 95 { 96 for (int j = 0; j < length-i-1; j++) 97 { 98 if (strcmp((stu[j].getNum()), stu[j + 1].getNum()) > 0) 99 //if (stu[j].getName().compare(stu[j+1].getName()) > 0) 100 { 101 //compare(stu[j].getName(),stu[j+1].getName()); 102 //stu[j].getName().compare(stu[j+1].getName()); 103 stu[j].swapStudent(stu[j + 1]); 104 } 105 } 106 } 107 cout << "學號降序排列" << endl; 108 for (int i = 0; i < length; i++) 109 { 110 stu[i].OutPutInfo(); 111 // if (i % 10 == 0) 112 // { 113 // cout << "按下任意鍵繼續顯示" << endl; 114 // getchar(); 115 // } 116 } 117 getchar(); 118 } 119 break; 120 case '2'://姓名 121 { 122 for (int i = 0; i < length; i++) 123 { 124 for (int j = 0; j < length - i - 1; j++) 125 { 126 if (strcmp(stu[j].getName(), stu[j + 1].getName()) < 0) 127 //if (stu[j].getNum().compare(stu[j+1].getNum()) > 0) 128 { 129 stu[j].swapStudent(stu[j + 1]); 130 } 131 } 132 } 133 cout << "姓名降序排列" << endl; 134 135 for (int i = 0; i < length; i++) 136 { 137 stu[i].OutPutInfo(); 138 // if (i % 10 == 0) 139 // { 140 // cout << "按下任意鍵繼續顯示" << endl; 141 // getchar(); 142 // } 143 } 144 getchar(); 145 } 146 break; 147 case '3'://性別 148 { 149 for (int i = 0; i < length; i++) 150 { 151 for (int j = 0; j < length - i - 1; j++) 152 { 153 if (stu[j].getSex() < stu[j + 1].getSex()) 154 { 155 stu[j].swapStudent(stu[j + 1]); 156 } 157 } 158 } 159 cout << "性別降序排列" << endl; 160 for (int i = 0; i < length; i++) 161 { 162 stu[i].OutPutInfo(); 163 // if (i % 10 == 0) 164 // { 165 // cout << "按下任意鍵繼續顯示" << endl; 166 // getchar(); 167 // } 168 } 169 getchar(); 170 } 171 break; 172 173 case '4'://學分 174 { 175 for (int i = 0; i < length; i++) 176 { 177 for (int j = 0; j < length - i - 1; j++) 178 { 179 if (stu[j].GetCredit() < stu[j + 1].GetCredit()) 180 { 181 stu[j].swapStudent(stu[j + 1]); 182 } 183 } 184 } 185 cout << "學分降序排列" << endl; 186 for (int i = 0; i < length; i++) 187 { 188 stu[i].OutPutInfo(); 189 // if (i % 10 == 0) 190 // { 191 // cout << "按下任意鍵繼續顯示" << endl; 192 // getchar(); 193 // } 194 } 195 getchar(); 196 } 197 break; 198 default: 199 break; 200 } 201 return true; 202 } 203 204 int GetNumberFromFile() 205 { 206 int count = 0;//對象個數,即學生人數 207 fstream infile("e:\\student.txt",ios::in | ios::binary); 208 if (!infile) 209 { 210 cout<<"open file error!"<<endl; 211 getchar(); 212 exit(0); 213 } 214 Student stu; 215 while (infile.read((char*)&stu,sizeof(stu))) 216 { 217 count++; 218 } 219 infile.close(); 220 return count; 221 } 復制代碼 復制代碼 1 #include "student.h" 2 #include "fstream" 3 #include "string" 4 5 int main() 6 { 7 char ch = Menu(); 8 int quit = 1; 9 while (quit) 10 { 11 switch (ch) 12 { 13 case '1'://成績錄入 14 { 15 Student stu1; 16 stu1.InputInfo(); 17 fstream outfile("e:\\student.txt", ios::app | ios::binary); 18 if (!outfile) 19 { 20 cerr << "open file error!"; 21 } 22 outfile.write((char*)&stu1, sizeof(stu1)); 23 outfile.close(); 24 25 ch = '0'; 26 getchar(); 27 } 28 break; 29 case '2'://成績顯示 30 { 31 fstream infile("e:\\student.txt",ios::in | ios::binary); 32 if (!infile) 33 { 34 cout<<"open file error!"<<endl; 35 getchar(); 36 //exit(0); 37 } 38 int len = 0; 39 len = GetNumberFromFile(); 40 if (len == 0) 41 { 42 cout << "no data!" << endl; 43 ch = '0'; 44 break; 45 } 46 Student *stu = new Student[len]; 47 cout << "number\tname\tsex\tyear-month-day\tcredit" << endl; 48 for (int i = 0; i < len;i++) 49 { 50 infile.read((char*)&stu[i], sizeof(stu[i])); 51 stu[i].OutPutInfo(); 52 } 53 delete []stu; 54 infile.close(); 55 ch = '0'; 56 getchar(); 57 } 58 break; 59 case '3'://排序管理 60 { 61 char condtion = SortMenu(); 62 fstream file("e:\\student.txt", ios::in | ios::binary); 63 if (!file) 64 { 65 cerr << "open file error!"; 66 } 67 int len = GetNumberFromFile(); 68 Student *stu = new Student[len]; 69 for (int i = 0; i < len;i++) 70 { 71 file.read((char *)&stu[i], sizeof(stu[i])); 72 } 73 74 file.close(); 75 SortByCondition(stu,len, condtion); 76 77 78 delete []stu; 79 getchar(); 80 } 81 break; 82 83 case '4'://學分管理 84 { 85 86 } 87 break; 88 89 case '0': 90 { 91 quit = 0; 92 exit(0); 93 ch = '0';//quit switch 94 } 95 break; 96 default: 97 //ch = '0'; 98 break; 99 } 100 //getchar(); 101 102 ch = Menu(); 103 } 104 system("pause"); 105 return 0; 106 }