使用类处理文件时出错
Error in file handling using classes?
代码是这样的:
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "nRoll no : ";
cin >> roll;
cout << "nMarks : ";
cin >> marks;
cout << "n";
}
void display(void)
{
cout << "n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
s1.display();
}
fil.close();
getch();
}
该程序即将使用类读取和写入学生的详细信息。
错误
如果我输入一次详细信息,输出会显示两次详细信息。
找到的输出
尼廷,罗尔诺 12 有 98% 的分数。尼廷,罗尔诺 12 有 98% 的分数。
预期输出
尼廷,罗尔诺 12 有 98% 的分数。
试试这个:
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "nRoll no : ";
cin >> roll;
cout << "nMarks : ";
cin >> marks;
cout << "n";
}
void display(void)
{
cout << "n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
if (feof(fil)) {
puts ("End-of-File reached.");
break;
}
s1.display();
}
fil.close();
getch();
}
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 在 C/C++ 中打开驻留在 "/sys/" 下的文件时出错
- 在头文件中定义变量不会出错
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 生成文件中隐式规则中的 -c 标志出错
- 编译时出错 - 链接.cpp和头文件
- 从人员矢量插入和读取文件时出错
- LNK2019 在文件中调用静态成员的方法时出错.cpp
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 猫鼬 - 包含标准C++库文件时出错
- 在f2c.h文件中定义min()max()宏时出错
- ASIOSDK;从hostsample.cpp生成mex文件时出错
- 使用emscripten将c++文件转换为wasm时出错
- 将文本从一个文件复制到另一个c++流时出错
- 在C++目录中搜索文件的函数输出中出错
- 编译包含LLVM API标头的C++文件时出错
- MySQL C++连接器:添加符号时出错:文件格式无法识别