C++while循环,使用if-else语句在数组中计数

C++ while loop, using if else statements to count in an array

本文关键字:数组 语句 循环 使用 if-else C++while      更新时间:2023-10-16

我在一个基本的c++程序分配中遇到了问题,非常感谢您的帮助。任务如下:

编写一个接受键盘输入的程序(使用输入按Enter键终止(,并计算字母(A-Z和A-Z(、数字(0-9(和其他字符的数量。使用cin输入字符串,并使用以下循环结构检查字符串中的每个字符,其中包含一个"if"语句和多个"else-if"语句。

到目前为止,我的程序是:

#include <iostream>
using namespace std;
int main()
{
char s[50];
int i;
int numLet, numChars, otherChars = 0;
cout << "Enter a continuous string of       characters" << endl;
cout  << "(example: aBc1234!@#$%)" <<      endl;
cout  << "Enter your string: ";
cin  >> s;
i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))
  {numLet++;
  }
else if (s[i] >= 48 && s[i] <= 57)
{numChars++;
    }
else if ((s[i] >= 33 && s[i] <= 4) || (s[i] >= 58  && s[i] <=64) ||  (s[i] >= 9 && s[i] <= 96) || (s[i]   >= 123 && s[i] <= 255))
  {otherChars++;
  }
  i++;
}
cout  << numLet << " letters" << endl;
cout << numChars << " numerical characters" << endl;
cout << otherChars << " other characters" << endl;
return 0;
}

字母计数给出的值有点太低,而数字计数给出的是一个很大的负数。其他字符似乎运行良好。

如另一个答案中所述,您需要初始化变量,但此代码中也有一个错误:

if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))

括号错了。因此,不管怎样,你都不会计算小写字母(我认为(——它应该是这样的(为了可见性而缩进(:

 if (
      (s[i] >= 'a' && s[i] <= 'z') ||
      (s[i] >= 'A' && s[i] <= 'Z')
      )

你也可以使用这个。既然你用的是c++而不是c,对吧;((这里的人显然对这种差异感到愤怒(

您需要将每个整数设置为0。实际上,您的代码只设置otherChars = 0。将该行设为numLet = 0, numChars = 0, otherChars = 0;