用c++实现输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2023-11-23 15:19:21 浏览: 77
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i;
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一行字符:");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isspace(str[i])) {
spaces++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
}
printf("其中英文字母个数:%d\n", letters);
printf("其中空格个数:%d\n", spaces);
printf("其中数字个数:%d\n", digits);
printf("其中其他字符个数:%d\n", others);
return 0;
}
相关问题
用c++输入一行字符,分别统计其中英文字母、空格、数字和其他字符的个数
好的,这个问题可以回答。请看下面的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, letters = , spaces = , digits = , others = ;
printf("请输入一行字符:\n");
fgets(str, 100, stdin);
for (i = ; str[i] != '\'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isspace(str[i])) {
spaces++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("空格个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return ;
}
```
希望这个回答能够帮到你。
用c++输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
以下是一个简单的 C 语言程序,可以输入一行字符并统计其中英文字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
int main() {
char c;
int letter_count = 0, digit_count = 0, space_count = 0, other_count = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n') {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
letter_count++;
} else if (c >= '0' && c <= '9') {
digit_count++;
} else if (c == ' ' || c == '\t') {
space_count++;
} else {
other_count++;
}
}
printf("其中英文字母个数:%d\n", letter_count);
printf("其中数字个数:%d\n", digit_count);
printf("其中空格个数:%d\n", space_count);
printf("其中其他字符个数:%d\n", other_count);
return 0;
}
```
在这个程序中,我们使用了 getchar() 函数来逐个读入字符,直到读到回车符为止。然后,我们使用 if-else 语句来判断每个字符属于哪个类别,根据情况递增相应的计数器。最后,我们打印出每个计数器的值,就能得到统计结果了。
阅读全文
相关推荐












