c语言:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2023-03-08 20:15:36 浏览: 69
答案:可以使用以下代码:int a_count = 0, b_count = 0, c_count = 0, d_count = 0;
char ch;
while((ch=getchar())!='\n'){
if(ch>='a' && ch<='z' || ch>='A' && ch<='Z')
a_count++;
else if(ch == ' ')
b_count++;
else if(ch>='0' && ch<='9')
c_count++;
else
d_count++;
}
printf("英文字母个数:%d\n空格个数:%d\n数字个数:%d\n其他字符个数:%d\n", a_count, b_count, c_count, d_count);
相关问题
C语言:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
好的,这个问题属于技术问题。以下是解答:
您可以使用一个循环来遍历输入的字符串,然后使用isdigit()、isalpha()、isspace()等函数来判断字符是否属于英文字母、数字或空格。然后分别统计它们的个数即可。代码示例:
```
#include<stdio.h>
#include<ctype.h>
int main(){
int alphabets=0, digits=0, spaces=0, others=0;
char input[100];
printf("请输入一行字符:");
fgets(input, 100, stdin);
for(int i=0; input[i]!='\0'; i++){
if(isalpha(input[i])){
alphabets++;
}
else if(isdigit(input[i])){
digits++;
}
else if(isspace(input[i])){
spaces++;
}
else{
others++;
}
}
printf("英文字母个数:%d\n", alphabets);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
您可以将输入的字符串存储在字符数组input中,并使用fgets()函数从标准输入中读取它。然后,循环遍历输入字符串中的每个字符,并使用相应的函数判断字符属于哪一类。然后,增加相应计数器的值。最后,输出四个计数器的值。
用C语言输入一行字符分别统计出其中英文字母空格数字和其他字符的个数
好的,这是一个经典的问题,以下是代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alphabets, digits, spaces, others;
alphabets = digits = spaces = others = 0;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alphabets++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("输入的字符串中包含:\n");
printf("%d 个字母\n", alphabets);
printf("%d 个数字\n", digits);
printf("%d 个空格\n", spaces);
printf("%d 个其他字符\n", others);
return 0;
}
```
希望这个回答能够帮到你!