为什么我的Delete()函数不起作用? [英] Why my Delete() Function doesn't work?

查看:111
本文介绍了为什么我的Delete()函数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码









Code below









void Staff::Delete() {
	char tgtIC[15];
	Staff objStaff;
	fstream iofile( "Employee.dat",ios::in || ios::out);
	if (!iofile) 				// overloaded ! operator 
	{ 														// or: if( outClientFile.fail() ) 
		cerr << "\t File could not be opened" << endl; 
		system( "PAUSE" ); 
		exit( 1 ); 					// prototype in cstdlib 
	} 
	fflush(stdin);				// To remove any previous content stored in memory
	cout<<endl;
	cout<< "\t ==================================================" 
	cout<< "\t < DELETE A RECORD >" <<endl;
	cout<< "\t Enter IC that you want to delete : " 
	cout<< "\t ==================================================" <<endl;

	cout<< "\t |      Enter Staff IC : " ;
	cin.getline(tgtIC, 15);
//==================================================" <<endl;

	iofile.read((char *) (&objStaff), sizeof(Staff));
	while (!iofile.eof())
	{	//cout<< "t :" <<tgtIC<< "obj : " <<objStaff.IC<<endl;
		if (!strcmp(tgtIC,objStaff.IC)==0)
			display(objStaff);
		else 
			cout<< "\t Delete record - by writing a blank record if using random file" <<endl;
		iofile.read((char *) (&objStaff), sizeof(Staff));
	} 
	iofile.close(); // explicit closing 
}

推荐答案

尝试使用调试器.


iofile.read((char *) (&objStaff), sizeof(Staff));


只是不适合我而已.您绝对应该通过调试器运行.您正在将一个Staff对象转换为字符数组,我敢打赌sizeOf(Staff)返回的数字大于您的转换表示的数组.导致错误.
iofile.read((char *) (&objStaff), sizeof(Staff));


Just doesn''t sit right with me. You definitely should run through the debugger. You are casting a staff object as a character array I would wager that sizeOf(Staff) is returning a number greater than the array your cast represents. Causing your error.


您要混合使用文本模式和二进制模式吗?

我建议您将ios :: binary标志与流构造器中的in和out结合使用.

无法真正确定,因为您的代码有些混乱,并且由于引号不匹配(以及其他原因)而显得不完整

另外,在正确的范围内声明变量.即使打开流失败,也会运行objStaff的构造函数.声明它尽可能接近动作.养成习惯. (但是在处理循环时会有例外)
Are you mixing text mode and binary mode?

I suggest you use the ios::binary flag combined with in and out in your stream constructor.

Can''t really tell for sure, since your code is a bit messed up and does not look complete due to mismatched quotes (and what else?)

Also, declare variables in the correct scope. The constructor of objStaff is run even if the stream opening fails. Declare it as close to the action as possible. Make that a habit. (There are exceptions however when dealing with loops)


这篇关于为什么我的Delete()函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆