我试图foo
通过使用预定义的功能检查字符串中的每个字符来计算字符串中的字母数isalpha()
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string foo = "aaaaaaa1";
int count=0;
for (int i=0;i<foo.length();i++)
{
if ( isalpha(foo[i]) == true)
{
count++;
}
}
cout<<count;
system("PAUSE");
}
预期产量:
7
电流输出
0
错误是function isalpha is not returning true for alphabetic
,
有人可以向我解释为什么以及如何解决该问题,以检查给定字符是否为字母
返回类型isalpha
是int
,不是bool
(来自C)。如果检查失败,则返回0,如果成功,则返回非零值。请注意,在这种情况下,它不必返回1。
比较a与将int
其true
提升true
为整数1。然后,对于1以外的整数,比较失败。
您永远不要通过与true
或进行比较来检查逻辑值false
-而是依赖于值或隐式转换:
if ( isalpha(foo[i]) )
{
count++;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句