您的位置:首页 > 其它

字符串是否为数字及有效性检查

2011-01-15 15:05 232 查看
在编写MFC窗体程序时,我们经常要判断用户输入的一个字符串是否合法有效,以此来增强程序的健壮性。

最近,在测试系统的对话框的输入时,发现存在大量这样的问题,甚至有一些特定变态的输入还导致系统异常退出。

为了解决这些问题,我编写下面这个头文件,来判断输入的字符串是否为数字,以及是否在有效范围之内。

希望以下代码对你有用!

#ifndef __CT3D__CHECKVALIDVAL__H__
#define __CT3D__CHECKVALIDVAL__H__

class CStringEx
{
private:
CString m_str;
int m_dot_count;

public:
CStringEx()
{
m_dot_count = 0;
}
CStringEx(const CString& s)
{
m_str = s;
}
virtual ~CStringEx()
{
}

public:
bool isFloat()
{
if (m_str.IsEmpty())
return false;

m_dot_count = 0;

int start_pos = 0;
char c = m_str.GetAt(0);
if (c=='+' || c=='-')
start_pos = 1;

int length = m_str.GetLength();
for (int i=start_pos; i<length; i++)
{
c = m_str.GetAt(i);
if (c=='.')
{
m_dot_count++;
continue;
}

if (c<0x30 || c>0x39)
return false;
}

if (m_dot_count>1) // ..23.
return false;
if (length==1 && (start_pos==1 || m_dot_count==1))// . or +
return false;
if (length==2 && start_pos==1 && m_dot_count==1) // +.
return false;

return true;
}

bool isInterger()
{
if (m_str.IsEmpty())
return false;

int start_pos = 0;
char c = m_str.GetAt(0);
if (c=='+' || c=='-')
start_pos = 1;

int length = m_str.GetLength();
for (int i=start_pos; i<length; i++)
{
c = m_str.GetAt(i);
if (c<0x30 || c>0x39)
return false;
}

if (length==1 && start_pos==1)// +
return false;

return true;
}

bool isValidFloat(double minVal, double maxVal, bool isHasMin=true, bool isHasMax=true)
{
if (maxVal<minVal)
{
double a = minVal;
minVal = maxVal;
maxVal = a;
}

if (!isFloat())
return false;

double d = atof(LPCTSTR(m_str));
if (isHasMin && d<minVal)
return false;
if (isHasMax && d>maxVal)
return false;

return true;
}

bool isValidInterger(int minVal, int maxVal, bool isHasMin=true, bool isHasMax=true)
{
if (maxVal<minVal)
{
int a  = minVal;
minVal = maxVal;
maxVal = a;
}

if (!isInterger())
return false;

int d = atoi(LPCTSTR(m_str));
if (isHasMin && d<minVal)
return false;
if (isHasMax && d>maxVal)
return false;

return true;
}
};

// 全局函数
class CStringValid
{
public:
static bool CStringValid::strIsFloat(const CString& s)
{
CStringEx sx = s;
return sx.isFloat();
}

static bool CStringValid::strIsInterger(const CString& s)
{
CStringEx sx = s;
return sx.isInterger();
}

static bool CStringValid::strIsFloatValid(const CString& s, double minVal, double maxVal, bool isHasMin=true, bool isHasMax=true)
{
CStringEx sx = s;
return sx.isValidFloat(minVal, maxVal, isHasMin, isHasMax);
}

static bool CStringValid::strIsIntergerValid(const CString& s, int minVal, int maxVal, bool isHasMin=true, bool isHasMax=true)
{
CStringEx sx = s;
return sx.isValidInterger(minVal, maxVal, isHasMin, isHasMax);
}
};

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: