c++ - 验证像 "-2-2"或 "--22"或 "2--2"这样的 CString 是无效的

标签 c++ visual-c++ mfc

在 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”),您可以轻松调整该方法。只是不要忘记将 fieldsRead 与正确的值进行比较。

关于c++ - 验证像 "-2-2"或 "--22"或 "2--2"这样的 CString 是无效的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984209/

相关文章:

c++ - Swig:ValueWrapper 和模板 BUG?

c++ - 禁用单个警告错误

c++ - 使用MAP文件 VS2010 MFC

c - VC2008 中的链接器是否存在路径中的空格问题?

c++ - visual C++ express 2010 和设置环境变量解决方案范围

.net - MFC 与 CLR?

mfc - 只需要 CListCtrl 控件中的某些行具有复选框

c++ - C++ 中的自定义迭代器

c++ - astar_search 在以 listS 作为顶点容器的图上?

c++ - 使用 initialization_list 导致歧义的函数重载