我试图通过迭代整个字符串并输出整数来测试字符串是否包含整数。我的方法涉及将字符串转换为 c-string ,atoi
c 字符串,然后使用测试它是否是整数isdigit
功能。由于某种未知的原因,isdigit
尽管函数遇到整数,但它返回 false。
我需要帮助解决这个问题
#include <iostream>
using namespace std;
#include <string>
int main()
{
string p = "[ab, e2cd]";
for (int k = 0; k < p.length(); k++)
{
if (isdigit(atoi(p.substr(k,1).c_str())) == true) //testing done here
{
cout << atoi(p.substr(k, 1).c_str());
}
}
}
isdigit http://en.cppreference.com/w/c/string/byte/isdigit需要一个int
与您所在区域中单个字符的值。可以通过它unsigned char
投射自char
,并让转换为int
做它的事。自从string
包含chars
,您可以像这样使用它的元素:
if ( static_cast<unsigned char>(isdigit(p[k])) ) { ....
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)