如何检查CString是否只包含数字字符

Roh*_*ews 7 cstring visual-c++ visual-c++-2005

我正在读取文件并解析其内容.我需要确保一个CString值只包含数字.我能实现的不同方法有哪些?

示例代码:

Cstring Validate(CString str)
{
  if(/*condition to check whether its all numeric data in the string*/)
  {
     return " string only numeric characters";
  }
  else
  {
     return "string contains non numeric characters";
  }
}
Run Code Online (Sandbox Code Playgroud)

hal*_*lex 17

您可以迭代所有字符并使用函数检查isdigit字符是否为数字.

#include <cctype>

Cstring Validate(CString str)
{
    for(int i=0; i<str.GetLength(); i++) {
        if(!std::isdigit(str[i]))
            return _T("string contains non numeric characters");
    }
    return _T("string only numeric characters");
}
Run Code Online (Sandbox Code Playgroud)

另一个不使用isdigit但仅使用CString成员函数的解决方案使用SpanIncluding:

Cstring Validate(CString str)
{
    if(str.SpanIncluding("0123456789") == str)
        return _T("string only numeric characters");
    else
        return _T("string contains non numeric characters");
}
Run Code Online (Sandbox Code Playgroud)