2012-06-20 37 views
0

我正在做一個哈夫曼樹,我已經完成了我的工作。但是當我讀取一個字符時發生了一個問題,它在第一部分中讀取的是零而不是空格「」。在閱讀中的錯誤文件處理C++

這是代碼。在文件處理過程中,該錯誤發生在decode函數中。

void huffmantree<h>::decode(){ 
    CString *st; 
hscll<h> * temp=new hscll<h>(); 
int h; 
    ifstream myfile; 
    myfile.open ("z://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaae.txt"); 
    myfile >>h; 
    cout<<h; 

    for(int i=0;i<h;i++) 
    {char temp9[100]; 
    char l; 

    myfile >>l; 
    temp->insert(l); 
    // myfile >> l ; 

     myfile >> temp9; 
     temp->atindex(i)->symboc.symbol=l; 
     temp->atindex(i)->code->setString(temp9); 
     //myfile >> '\n'; 
    } 
    _getch(); 

    //CString u; 
    //char k; 
    //int p=0; 
    //for(int i=0;i<st->m_length;i++) 
    //{ 
    // for(int j=0;j<8;j++) 
    // { 
    //  
    //  char a; 
    //  a=st->charAt(i); 
    //  int temp=1; 
    //  if(j==0) 
    //   temp=1; 
    //  if(a!='0') 
    //  { 
    //   for(int y=0;y<j;y++) 
    //    { 
    //      temp*=2; 
    //    } 
    //   p+=temp; 
    //  } 
    //  else 
    //  { 
    //  p+=0; 
    //  
    //  } 

    //  i++; 
    //  cout<<a; 
    // } 
    // k=p; 
    // char t=7; 
    // //cout<<"  "<<t<<" "<<p<<endl; 
    // myfile << k; 
    // p=0; 
    // u.addcharbychar(k); 
    //} 
    ////cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<u.getString(); 
    ////cout<<endl<<endl<<endl<<"the length is =="<<u.m_length<<endl; 
    myfile.close(); 
} 

回答

2

如果使用>>輸入,領先的空白將被跳過。如果您正在讀取二進制數據,則需要以二進制模式打開文件(myfile.open(name, std::ios::in | std::ios::binary)並使用非格式化輸入函數,如istream::get()。 (並且在寫入時,還需要編寫二進制文件。)

+0

可以通過使用['std :: ws'](http://en.cppreference.com/w/cpp/io)來避免空白/ manip/ws) – rubenvb

+0

你的意思是'std :: noskipws'; 'std :: ws'顯式跳過空格。你可以,但使用爲這類工作設計的功能更自然。 –

+0

是的,'std :: noskipws'。不知何故,我認爲這是一個二進制切換...我的錯誤。 – rubenvb