gpt4 book ai didi

visual-c++ - 如何检查字符串是否仅包含数字字符

转载 作者:行者123 更新时间:2023-12-04 10:01:11 27 4
gpt4 key购买 nike

我正在从文件读取并解析其内容。我需要确保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");
}

关于visual-c++ - 如何检查字符串是否仅包含数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12776938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com