2012-03-19 96 views
2

下面的代碼應該從輸入中讀取記錄並將它們存儲在名爲file.dat的文件中。然後它應該按升序排列這些記錄,但出於某種原因程序掛在第二行while循環的「file1.seekg( - (sizeof(r)),std :: ios :: cur);」。有人可以告訴我有什麼問題嗎?程序由於某種原因掛起

#include <iostream> 
#include <fstream> 
#include <strstream> 

int main() 
{ 
std::ofstream file; 
file.open("file.dat",std::ios::trunc|std::ios::binary); 
if(!file) 
    std::cout<<"unable to open for output"; 

struct record 
{ 
    char code[6]; 
    char name[20]; 
    int i; 
}; 

record r; 
int a = 0; 

while(1) 
{ 
    std::cout<<"Record " << a + 1 << std::endl; 
    std::cout<<"Enter character code, name and an int \n"; 
    std::cin.ignore(); 
    std::cin.getline(r.code,6); 
    std::cin.getline(r.name,20); 
    std::cin>>r.i; 
    file.write((char *)&r,sizeof(r)); 
    std::cout<<"\nAdd another (y\\n) : "; 
    char c; 
    std::cin>>c; 
    if(c == 'n') 
     break; 
    a++; 
    std::cout<<'\n'<<'\n'; 
} 
file.close(); 

std::fstream file1("file.dat",std::ios::in|std::ios::out|std::ios::binary); 
if(!file1) 
    std::cout<<"unable to open file1"; 

else 
{ 
    if(a>0) 
    { while(a) 
     { 
      file1.seekp(0); 
      for(int i = a; i>0;i--) 
      { 
       record r1; 
       file1.read((char *)&r,sizeof(r)); 
       file1.read((char *)&r1,sizeof(r1)); 
       if(r1.i < r.i) 
       { 
        file1.seekp(-(sizeof(r)*2),std::ios::cur); 
        file1.write((char *)&r1,sizeof(r)); 
        file1.write((char *)&r,sizeof(r)); 
        file1.seekg(-(sizeof(r)),std::ios::cur); 
       } 
      } 

      a--; 
     } 
    } 
    file1.close(); 
} 

std::ifstream file2("file.dat",std::ios::binary); 
if(!file2) 
    std::cout<<"unable to open file2"; 
    else 
while(1) 
{ 
    std::cout<<"\n\n"; 
    file2.read((char *)&r,sizeof(r)); 
    if(file2.eof()) 
     break; 
    std::cout<<r.code<<'\t'<<r.name<<'\t'<<r.i; 
} 
} 
+2

你知道它掛起?這些信息會有幫助。此外,您可以嘗試最小化示例代碼大小。 – heinrich5991 2012-03-19 07:19:33

+1

使用調試器並單步執行代碼;這就是它的... – trojanfoe 2012-03-19 07:25:27

+0

'std :: get.ignore'那是什麼? – 2012-03-19 07:26:35

回答

2

第一

變化的std :: get.ignore - >的std :: cin.ignore()

,如果你要放棄一個字符。

它編好,FILE.DAT文件創建..

你可能會檢查該記錄內FILE.DAT雖然

2

如果你想忽略新線的實際DAT後輸入的字符,然後你必須使用:

std::cin.ignore(); 

如果您想使用的ignore更多的參考去這個LINK

+0

對不起,這是我的一個錯字,我編輯過這個帖子...程序掛在第二行while循環中file1.seekg( - (的sizeof(R)),標準:: IOS :: CUR);」。 Plz的幫助。 – user1232138 2012-03-19 10:38:53

+0

請更新問題,以便其他用戶也可以幫助您 – 2012-03-19 10:42:06