需要帮助调试更新二进制文件的函数

时间:2013-01-13 14:28:16

标签: c++ debugging binaryfiles

void updatebfile(char filename[MAX])
{

fstream writereadb;

char cont='y';
char filenameb [MAX];
int i=1;
int record;

student s;

strcpy(filenameb,filename);
strcat(filenameb,".dat");

writereadb.open(filenameb,ios::in | ios::out | ios::binary  );


cout<<"------------------------------"
    <<endl;

cout<<"Begin updating of binary file "
    <<filenameb
    <<endl
    <<endl;

cout<<"Information for student file"
    <<endl
    <<endl;


while ( writereadb.read (reinterpret_cast <char *>(&s), sizeof (s) ) )
{

    cout<<i
        <<'\t'
        <<s.identity
        <<" "
        <<s.name
        <<endl;

    i++;


}
writereadb.clear();

do
{   
cout<<endl
    <<"Update record: ";
cin>>record;

cout<<endl
    <<"Student id: ";   

writereadb.seekg ( (record - 1) * sizeof(s), ios::beg);
writereadb.read (reinterpret_cast <char *>(&s), sizeof (s));    

cout<<s.identity
    <<endl; 

cout<<"Update the name: "; 
cin.getline(s.name,50); //My programme does not stop at this line to read in an input for some reason
//cin.clear();
    //cin.ignore(200,'\n'); 

writereadb.seekp((record-1)*sizeof(student),ios::beg);  
writereadb.write (reinterpret_cast <const char *>(&s), sizeof (s));

cout<<"Any more update (y/n) :";
cin>>cont;//

}while (cont=='y');

writereadb.close();
 }

我的程序工作正常,但在程序结束时遇到cin.getline(s.name,50)。程序不会停止读取输入并继续运行。

我尝试将cin.clear(); cin.ignore;放在cin.getline(s.name,50)之后,它可以正常工作,但它不会将s.name存储到二进制文件中。

2 个答案:

答案 0 :(得分:1)

添加cin.ignore(); 恰好在cin.getline(s.name,50);

之前

答案 1 :(得分:0)

我必须添加

  

cin.clear();

     

cin.ignore(200, '\ n');

使用&gt;&gt;清除'\ n' cin&gt;&gt;

期间的运算符