C++ 文件处理 - 类对象
c++ file handling - class objects
下面的代码读取 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
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 使用对象数组对 SFML 进行动画处理
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 使用对象的基类部分模板专用化对对象进行哈希处理::哈希
- C++:处理线程本地对象销毁
- 传递多处理.将对象值为 ctype 函数?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 使用返回对象的函数处理错误
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?
- C++如何处理同名对象的向量?
- static是如何使用ClassA::m_variable处理所有类对象的
- 当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
- 处理无法按预期方式创建的对象,c++
- 我可以将类作为C 中的对象处理
- QT良好的全局变量/对象处理
- 如何将map和unordered_map作为同一对象处理
- 强制一个对象处理输入的信号