如何在VC++ CString中验证有效的整数和浮点数

Kri*_*nan 3 c++ mfc

有人可以告诉我一种有效的方法来验证CString对象中存在的数字是有效整数还是浮点数?

Fré*_*idi 6

使用_tcstol()_tcstod():

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

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

编辑:修改代码以遵循评论中提供的优秀建议.