C函数检查char是否为大写字母并计算给定字符串中大写字母的数量

新手上路,请多包涵

我尝试编写一个 C++ 函数来检查 char 是否是给定字符串中的大写字母。

这是我的尝试:

 #include<iostream>
#include <conio.h>
#include<string>
using namespace std;
int iscapital(char x)
{
 if (x>='A'&&x<='Z')    return 1;

 else  return 0;
}
main()
{
char a[20];int len; int c=0;
cout<<"enter your line: ";
cin>>a;
len=strlen(a);
for (int i=0;i<=len;i++)
iscapital(a[i]);
if (iscapital)
{
    c++;
}

cout<<"capital letter in string is: "<<c;
}

原文由 Ibra OpEd 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 487
2 个回答

您的代码应如下所示:

 int iscapital(char x)
{
       if (x >='A' && x <= 'Z')    return 1;
       else  return 0;
}

int main()
{
  char a[20];int len; int c=0;
  cout<<"enter your line: ";
  cin.getline(a , 20);
  // Note : ' getline ' will read the entire line written in the console and will stop only at the end line mark...will include and the white spaces .
  // http://stackoverflow.com/questions/4745858/stdcin-getline-vs-stdcin

  len=strlen(a);
  for (int i = 0;i < len;i++)
  {
    if (iscapital(a[i]))
    {
       c++;
    }
  }
  cout<<"capital letter in string is: "<<c;

  return 0;
 }

原文由 Reznicencu Bogdan 发布,翻译遵循 CC BY-SA 3.0 许可协议

您没有正确使用 iscapital

 for (int i=0;i<=len;i++)
    iscapital(a[i]); // Call the function, ignore the result
if (iscapital)   // <- This is not valid C++
{
    c++;
}

你想要的是这个

for (int i=0;i<=len;i++)
    if (iscapital(a[i]))
    {
        c++;
    }

正如其他人评论的那样,查找 std::isupper 以了解字母是否为大写字母,并查找 std::count、std::count_if 以计算值的出现次数或条件为真的次数。

此外, main 应该返回 intiscapital 应该返回 bool 使用 int 表示真值或假值已过时,不应在新代码中使用。最后,考虑使用 std::string 而不是 char [] 。使用字符数组来表示字符串是 C 的做事方式。 C++ 使用 std::string 有很多微妙的问题。

原文由 François Andrieux 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题