c++ 字符串读写

这几天一直在解决座位号重复问题,所以考虑到用文件读写来判断字符串是否重复。


刚开始是使用固定的长度来写入文件和替换字符串,但是考虑到代码的复用性,后来还是修改了任意字符串的读写和替换,方便以后使用。


1:添加字符串到文件:

函数原型:bool AddSeatID(char *_setNum,int length);

函数实现:

bool CFileTest::AddSeatID(char *_setNum,int length)
{
	if (checkDuplicate(_setNum))
	{
		return false;
	}
	if (!openFile("ab+"))
	{
		printf("open file failed \n");
		return false;
	}
	char seatBuf[length+4];
	memset(seatBuf,0,length+4);
	memcpy(seatBuf,"[",1);
	memcpy(seatBuf+1,_setNum,length);
	memcpy(seatBuf+length+1,"]\r\n",3);
	fseek(m_fp,0L,SEEK_END);
	fwrite(seatBuf,length+4,1,m_fp);
	closeFile();
	m_seatIDList.push_back(_setNum);

	return true;
}
已追加方式写入文件,其中有使用判断字符串是否存在于文件中,如果有存在则返回false,不存在则写入文件。其中设置m_seatIDList为vector容器,将字符串保存到内存中


2:字符串重复判断函数:

函数原型:bool checkDuplicate(char* _seatID);

函数实现:

bool CFileTest::checkDuplicate(char* _seatID)
{
	string seatID;
	if (m_seatIDList.empty())
	{
		return false;
	}
	vector<string>::iterator iter;
	vector<string>::iterator beginVec = m_seatIDList.begin();
	vector<string>::iterator endVec = m_seatIDList.end();

	for (iter = beginVec; iter!= endVec; iter++)
	{
 		if (!strcmp(iter->c_str(),_seatID))
		{
			return true;
		}
	}
	return false;
}
将需要判断重复的字符串传入,并将此字符串与文件中读出的字符串进行比较


3:替换新旧字符串函数:

函数原型:bool changeSeatID(char* _oldSeat,int _oldLength,char* _newSeat,int _newLength);

函数实现:


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值