錯誤代碼:
struct STUD { int ID;//學號 char name[20]; float score; }stud; STUD SS[10]; student.open("student.dat",ios::in|ios::binary); if(!student) { cout<<"打開文件失敗!"<<endl; return 0; } int j=0; student.read((char *)&stud,sizeof(stud)); while(!student.eof()){ SS[j].name=stud.name;//報錯! SS[j].ID=stud.ID; SS[j].score=stud.score; j++; student.read((char *)&stud,sizeof(stud)); } student.close();
這段代碼的目的是從文件.dat中讀取數據,存儲到結構體數組對象SS[j]中,但是對SS[j].name賦值是報錯,改成了strcpy(SS[j].name,stud.name)即可,這里若用等號需要重載運算符=。注意添加頭文件#include<cstring>