2010-10-27 13 views

回答

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()); 
} 

編輯:修改代碼跟隨在評論中提供的很好的建議。

+1

捕獲結果通常也很有用。大多數時候你打算使用數值,如果它驗證。 – MSalters 2010-10-27 08:31:20

+1

只是注意到文本中的空字符串也返回true。在開始時檢查任何空字符串的附加檢查可能會有用。 – Clemens 2012-05-24 16:13:08

+1

@ xml-tools.com,非常真實,我添加了一個'NUL'字符檢查來實現這一點。感謝:) – 2012-05-24 17:11:47

相關問題