C++while循环,使用if-else语句在数组中计数
C++ while loop, using if else statements to count in an array
我在一个基本的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;
。
相关文章:
- 比较if语句中的数组值和int值
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 有人可以解释一下吗?这是关于数组和数组内部 if 语句的一些处理
- 在编译时自动生成用于稀疏数组索引的switch语句
- C++ 将二维数组索引与条件语句中的函数值进行比较
- 如果带有字符数组的语句无法正常工作
- 如何在Char数组中搜索Char在IF条件语句中
- 使用 if (? 运算符) 语句传递带有指针的数组
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- If/Else 语句在 2D 数组中移动时出现问题
- 显示使用函数、switch 语句和多维数组的程序的多个不合逻辑的错误
- 2D数组-将三个元素与if语句进行比较
- visual在C++中的if语句中的数组中使用特定值
- for 语句内的动态数组
- 如何使用嵌套的 if 语句检查字符数组
- 无法弄清楚为什么我的程序在条件不为真时执行 if 语句(数组)
- 正在尝试使用if语句检查数组数据
- 如何在不使用if语句的情况下查找数组中的最大值和最小值
- 将字符串存储在要在 IF 语句中使用的数组中的可能方法