tags:

views:

39

answers:

1

Can some one tell me a valid way to validate a number present in CString object as either a valid integer or floating number?

+1  A: 

Use _tcstol() and _tcstod():

bool IsValidInt(const CString& text, long& value)
{
    LPCTSTR ptr = (LPCTSTR) text;
    LPTSTR endptr;
    value = _tcstol(ptr, &endptr, 10);
    return (endptr - ptr == text.GetLength());
}

bool IsValidFloat(const CString& text, double& value)
{
    LPCTSTR ptr = (LPCTSTR) text;
    LPTSTR endptr;
    value = _tcstod(ptr, &endptr);
    return (endptr - ptr == text.GetLength());
}

EDIT: Modified the code to follow @MSalters's suggestion below.

Frédéric Hamidi
It's often useful to capture the result as well. Most of the times you intend to use the numerical value if it validated.
MSalters