验证像 "-2-2" 或 "--22" 或 "2--2" 这样的 CString 是否有效



C++如何验证像"-2-2"或"--22"或"2--2"这样的CString不是有效的整数。

我尝试了以下代码:

// CString input in the edit box that needs to be verified
   CString input_to_editbox
// verify its a number or not
   if (input_to_editbox.SpanIncluding(L"-0123456789") == input_to_editbox)
   //numeric
   AfxMessageBox(L"it is an integer");
   else
   //Non numeric
   AfxMessageBox(L"Not an integer");
但我无法验证"-2-2"或"-

-22"或"2--2"是非法和错误的整数。

我在使用DDX_函数时遇到了同样的问题,这些函数对它们的输入不是很严格。我已经用scanf(或更好的_stscanf_s)解决了这个问题。

int nValue;
unsigned charsRead = 0;
const int fieldsRead = _stscanf_s(str, _T("%d%n"), &nValue, &charsRead);
if(fieldsRead == 1  &&  charsRead == _tcslen(str)) {
    // We have read all fields and we have read the complete string,
    // so str contains a valid pattern.
}

如果要读取其他类型(例如"%u%n")或多个值(例如"rate is: %d/%d Mbits/s%n"),则可以轻松调整该方法。只是不要忘记将字段读取与正确的值进行比较。

最新更新