标题:C++不定长字符串比较合理且简单的解决方法
只看楼主
shitainong
Rank: 1
等 级:新手上路
帖 子:70
专家分:0
注 册:2012-7-6
结帖率:0
 问题点数:0 回复次数:1 
C++不定长字符串比较合理且简单的解决方法
C++不定长字符串比较合理且简单的解决方法



// testrealloc.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define XString_LENGTH 1024 // 默认缓存区的长度www.

class XString
{
char *m_x;
unsigned int m_size;

public:

XString();
~XString();
unsigned int GetSize();
unsigned int GetData(char *&pData);
bool AddData(char *pData, unsigned int nLen);
};

XString::XString()
{
m_size = 0;
m_x = (char*)malloc(XString_LENGTH);
}

XString::~XString()
{
if (m_x)
{
free(m_x);
m_x = NULL;
}
}

unsigned int XString::GetSize()
{
return m_size;
}

unsigned int XString::GetData(char * &pData)
{
pData = (char*)malloc(m_size+1);

if (!pData)
return 0;

memcpy(pData, m_x, m_size);
pData[m_size] = NULL;

return m_size+1;
}

bool XString::AddData(char *pData, unsigned int nLen)
{
if (nLen <= 0)
return false;

if (! pData)
return false;

unsigned nOldSize = m_size;
m_size += nLen;
if (m_size > XString_LENGTH)
{
// int n = m_size - XString_LENGTH;
char *p = m_x;
m_x = (char*)realloc(m_x, m_size);
if (!m_x)
{
m_x = p;
return false;
}

memcpy(m_x+nOldSize, pData, nLen);
// m_x[m_size]=NULL;
// printf("%s-%d\n", m_x, m_size);
// getchar();
}
else
{
memcpy(m_x+nOldSize, pData, nLen);
}

return true;
}

void k() // www.
{
XString a;
for (int i=0; i<3000; i++)
{
if (! a.AddData("88888888", 8))
{
printf("add data failed.\n");
}
}
getchar();
}
int main(int argc, char* argv[])
{
for(int i=0; i<100; i++)
{
k();
}
getchar();
return 0;
}
搜索更多相关主题的帖子: 1024 include public 字符串 
2012-07-13 15:51
pangding
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:北京
等 级:贵宾
威 望:94
帖 子:6784
专家分:16751
注 册:2008-12-20
得分:0 
这个是教学帖吗?
2012-07-14 12:16



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-373316-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.179810 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved