我正在读取文件并解析其内容.我需要确保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";
}
}
解决方法
您可以迭代所有字符并使用函数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");
}
另一个不使用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");
}