首页 > 解决方案 > 在 C++ 中处理文件期间的文件写入问题

问题描述

在制作一个练习文件处理的程序时,我遇到了一个问题。在写入文件期间,我看到如下奇怪的东西,即使我将文件保存为 txt 格式并在记事本中打开。

文件图片

谁能澄清一下?下面是编写代码:

int hostel::add()
{
int r,flag;
ofstream fout;
fout.open("model",ios::app);
cout<<"\n Enter Customer Details";
cout<<"\n **********************";
cout<<"\n\n Room no: ";
cin>>r;
flag=check(r);
if(flag){
cout<<"\n Sorry..!!!Room is already booked";
fout.close();
}
else

{
room_no=r;
cout<<"\n Name:\t ";
cin>>name;
cout<<"\n Address:\t ";
cin>>address;
cout<<"\n Phone No:\t ";
cin>>phone;
fout.write((char*)this,sizeof(*this));
fout.close();
cout<<"\n Your Room is booked!!";
    }

cout<<"\n Press any key to continue!!";
system("pause");
return 0;
}

同样在读取文件时最后一条记录被打印 2 次:

读取文件图片

阅读代码如下:

int hostel::rooms()
{
    ifstream fin("model",ios::in);

    cout<<"\n\t\t\tList Of Rooms Allotted";
    cout<<"\n\n Room No.\tName\t\tAddress\t\tPhone No.\n";
    while(!fin.eof())
    {
        fin.read((char*)this,sizeof(*this));
        cout<<"\n\n"<<room_no<<"\t\t"<<name;
        cout<<"\t\t"<<address<<"\t\t"<<phone;
    }

    cout<<"\n\n\n\t\t\tPress any key to continue!!";
    system("pause");
    fin.close();
    return 0;
}

标签: c++file-handling

解决方案


推荐阅读