您的位置:首页 > 其它

VC中判断是否数字的方法

2012-02-28 15:47 302 查看
方法一:

int IsNum(CString str)

{

if (str.IsEmpty())

return - 1;

int nDot = 0;

//数值只能是0到9及小数点组成

for (int i = 0; i < str.GetLength(); i++)

{

char ch = str.GetAt(i);

if ('.' == ch)

//小数点

{

nDot++;

continue;

}

if (ch >= '0' && ch <= '9')

//数字

continue;

return - 2; //非法字符

}

if (nDot > 1)

return - 3;

//小数点多于两个

else if (0 == nDot)

return 1;

//整数

else if (1 == nDot)

return 0;

//浮点数

return - 1000; //未知错误

}

方法二:

bool IsNumber( LPCTSTR pszText )

{

ASSERT_VALID_STRING( pszText );

for( int i = 0; i < lstrlen( pszText ); i++ )

if( !_istdigit( pszText[ i ] ) )

return false;

return true;

}

VC中判断是日期的方法

bool IsDate( LPCTSTR pszText )

{

ASSERT_VALID_STRING( pszText );

// format should be 99/99/9999.

if( lstrlen( pszText ) != 10 )

return false;

return _istdigit( pszText[ 0 ] )

&& _istdigit( pszText[ 1 ] )

&& pszText[ 2 ] == _T('/')

&& _istdigit( pszText[ 3 ] )

&& _istdigit( pszText[ 4 ] )

&& pszText[ 5 ] == _T('/')

&& _istdigit( pszText[ 6 ] )

&& _istdigit( pszText[ 7 ] )

&& _istdigit( pszText[ 8 ] )

&& _istdigit( pszText[ 9 ] );

}

以下是数字和日期的比较大小

int NumberCompare( LPCTSTR pszNumber1, LPCTSTR pszNumber2 )

{

ASSERT_VALID_STRING( pszNumber1 );

ASSERT_VALID_STRING( pszNumber2 );

const int iNumber1 = atoi( pszNumber1 );

const int iNumber2 = atoi( pszNumber2 );

if( iNumber1 < iNumber2 )

return -1;

if( iNumber1 > iNumber2 )

return 1;

return 0;

}

int DateCompare( const CString& strDate1, const CString& strDate2 )

{

const int iYear1 = atoi( strDate1.Mid( 6, 4 ) );

const int iYear2 = atoi( strDate2.Mid( 6, 4 ) );

if( iYear1 < iYear2 )

return -1;

if( iYear1 > iYear2 )

return 1;

const int iMonth1 = atoi( strDate1.Mid( 3, 2 ) );

const int iMonth2 = atoi( strDate2.Mid( 3, 2 ) );

if( iMonth1 < iMonth2 )

return -1;

if( iMonth1 > iMonth2 )

return 1;

const int iDay1 = atoi( strDate1.Mid( 0, 2 ) );

const int iDay2 = atoi( strDate2.Mid( 0, 2 ) );

if( iDay1 < iDay2 )

return -1;

if( iDay1 > iDay2 )

return 1;

return 0;

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