C++ 文件处理 - 类对象

c++ file handling - class objects

本文关键字:对象 处理 文件 C++      更新时间:2023-10-16

下面的代码读取 3 obj 并将它们写入一个文件。但是,我无法使用以下代码正确检索对象。数据重复且不按顺序排列

请帮忙

旧代码 :

#include<fstream.h>
#include<conio.h>
class mail
{
  public:
    char un[25];             // user name
    char pd[25];             // passsword
    void reg(int);
} obj[5];
void mail::reg(int k)
{
  int i;
  i=k;
  clrscr();
  cout<<"Enter user name ( enter unique name )n";
  cin>>un;

  cout<<"Enter passwordn";
  cin>>pd;
  ofstream filout;
  filout.open("email",ios::app||ios::binary);
  if(!filout)
  {
    cout<<"cannot open filen";
  }
  else
  {
    cout<<"n "<<i;
    filout.write((char *)&obj[i],sizeof(mail));
    filout.close();
  }
  cout<<"You are now registered. n";
  getch();
}        // end of sign up or register func
void main()
{
  int t;
  clrscr();
  obj[0].reg(0);
  obj[1].reg(1);
  obj[2].reg(2);
  mail obj2;
  ifstream filein;
  filein.open("email",ios::in||ios::binary);
  if(!filein)
  {
    cout<<"Unable to open file to readn";
  }
  else
  {
    while(!filein.eof())
    {
      filein.read((char *)&obj2,sizeof(obj2));
      cout<<"username "<<obj2.un<<" passwword "<<obj2.pd<<"n";
    }
    filein.close();
  }
  getch();
}

另外,请告诉我如何将代码放入堆栈溢出中。复制粘贴后手动放置4个空格非常烦人

更改后的新代码:

#include<fstream.h>
#include<conio.h>
struct mail
{
    char un[25];             // user name
    char pd[25];             // passsword
    void reg(int);
} obj[5];
void mail::reg(int k)
{
    int i=k;
    clrscr();
    cout<<"Enter user name ( enter unique name )n";
    cin>>un;
    cout<<"Enter passwordn";
    cin>>pd;
    ofstream filout;
    filout.open("email",ios::app|ios::binary);
    if(!filout) {
        cout<<"cannot open filen";
    } else {
        cout<<"n "<<i;
        filout.write((char *)&obj[i],sizeof(mail));
        filout.close();
    }
    cout<<"You are now registered. n";
    getch();
}   // end of sign up or register func
int main()
{
    int t;
    clrscr();
    obj[0].reg(0);
    obj[1].reg(1);
    obj[2].reg(2);
    mail obj2;
    ifstream filein;
    filein.open("email",ios::in|ios::binary);
    if(!filein) {
        cout<<"Unable to open file to readn";
    } else {
        while(filein) {
            filein.read((char *)&obj2,sizeof(obj2));
            cout<<"username "<<obj2.un<<" passwword "<<obj2.pd<<"n";
        }
        filein.close();
    }
    getch();
}

我仍然面临问题。我写3个对象。但是我得到了 4 条输出记录。最后一个是重复的。

您有一个不正确的文件循环,EOF() 循环是一种不好的做法,通常会导致未定义的行为,正确的循环如下所示:

filein.read((char *)&obj2,sizeof(obj2));
while(filein)
{
    cout<<"username "<<obj2.un<<" passwword "<<obj2.pd<<"n";
    filein.read((char *)&obj2,sizeof(obj2));
}

此循环的结构允许文件在再次读取之前检查文件的 EOF,而 EOF 循环将在 THEN 检查中读取 EOF,导致最后出现一些垃圾。

  • 你的fileIn变量使用不正确的标志,你使用'||'逻辑OR运算符,而不是 ' |' 逻辑按位运算符。这可能是一个错误的可能原因。
  • 您的程序有一些问题,void main()大多数这里的人畏缩,主要总是返回int