2012-12-17 126 views
0
class Student 
{ 
public: 
Student *prev; 
char S_Name[15]; 
char F_Name[15]; 
int Reg_Num; 
char Section; 
char MAoI[15]; 
float CGPA; 
Student *next; 
} 

我上面的類,我想將數據寫入到鏈接列表的二進制文件,當我退出程序,並重新讀回,並形成鏈接列表在程序運行時。 我已經嘗試過,但幾次嘗試失敗!輸入數據的代碼`Student * Add_Entry() { Student * temp = new Student();讀取和寫入類數據的二進制文件在VC++

char s_Name[15]; 
char f_Name[15]; 
int reg_Num; 
char section; 
char mAoI[15]; 
float cGPA; 

cout <<"**********************Menu***************************\n "; 
cout<<"\nEnter the Studets name \""; 
cin>>s_Name; 

cout<<"\nEnter Father`s name \""; 
cin>>f_Name; 

cout<<"\nEnter the Registration Number \""; 
cin>>reg_Num; 

cout<<"\nEnter the Section \""; 
cin>>section; 

cout<<"\nEnter the Major Area of Interest \""; 
cin>>mAoI; 

cout<<"\nEnter the Current CGPA \""; 
cin>>cGPA; 

strcpy_s(temp->S_Name,s_Name); 
strcpy_s(temp->F_Name,f_Name); 
temp->Reg_Num=reg_Num; 
temp->Section=section; 
strcpy_s(temp->MAoI,mAoI); 
temp->CGPA=cGPA; 
temp->next=NULL; 
temp->prev=NULL; 
return temp; 

//temp=Create_node(s_Name,f_Name,reg_Num,section,mAoI,cGPA);  

}`

要從文件中讀取我使用`字符*緩衝液;

ifstream reader; 
    reader.open("student.bin",ios::in | ios::binary); 
    if(reader.is_open) 
    { 
     do 
     { 
      reader.read(buffer,ch); 
      if(Header==NULL) 
      { 
       Header=(Student)*buffer; 
       temporary=Header; 
      } 

      else 
      { 
       temporary->next=(Student)*buffer; 
       temporary=temporary->next; 
      } 
     }while(buffer!=NULL); 
    } 

`

和寫入我使用`臨時=報頭; //備份條目 ofstream writer; (「student.bin」,ios :: out | ios :: binary);

   while(temporary!=NULL) 
       { 
        writer.write((char)* temporary,sizeof(temporary)); 
        temporary=temporary->next; 
       } 

       writer.close(); 

`

+1

可以從您最近一次嘗試張貼代碼嗎? – simonc

+0

你能編輯你的問題,以顯示你如何創建鏈表以及如何將它寫入文件嗎? – simonc

+1

像以前一樣,請編輯您的問題以包含此信息。你能否也解釋一下代碼是如何「失敗」的?如果它崩潰,請嘗試確定發生哪一行。如果代碼運行但給出令人驚訝的輸出,請解釋您看到的輸出以及您的期望。 – simonc

回答

0

這條線:

Header=(Student)*buffer; 

表示:執行緩衝,這可能是爲char指針,並取消對它的引用,得到char。然後將該char轉換爲Student。編譯器不知道如何將char轉換爲Student

相反,如果你這樣做:

Header= *((Student *)buffer); 

將指針強制轉換爲正確類型的指針,然後取消對它的引用給一個結構,它可以被複制。

你這樣做到處都是。

另外,閱讀時,不要填寫最後一項的「下一個」指針,也不要填寫「先前」指針。儘管最後保存的項目中的「下一個」指針可能爲零(假設它已正確保存),但預先指針可指向任何內容。最佳做法是正確地初始化所有內容。

另外:

if(reader.is_open) 

應該是:

if(reader.is_open()) 
+0

那麼我怎樣才能引用指針呢? –

+0

我需要將單個條目寫入文件並將其讀回嗎? –

+0

你應該可以做更多或更少的工作,但是你需要按照描述修正錯誤(也許更多)。我注意到你已經接受了我的答案 - 如果你還有其他問題,你應該提出一個新問題。如果我沒有真正回答你的問題,你應該用更多的信息更新你的問題。 – JasonD

相關問題