方法一:
#include <stdio.h>
#include <ctype.h> // 引入ctype.h头文件以使用isalpha, isspace, isdigit等函数
int main() {
char ch;
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一行字符:\n");
// 读取字符直到遇到换行符或EOF
while ((ch = getchar()) != '\n' && ch != EOF) {
if (isalpha(ch)) { // 判断是否为英文字母
letters++;
} else if (isspace(ch)) { // 判断是否为空格
spaces++;
} else if (isdigit(ch)) { // 判断是否为数字
digits++;
} else {
others++; // 其他字符
}
}
// 输出统计结果
printf("英文字母个数: %d\n", letters);
printf("空格个数: %d\n", spaces);
printf("数字个数: %d\n", digits);
printf("其他字符个数: %d\n", others);
return 0;
}
在这个程序中,我们使用了ctype.h
头文件中的isalpha、isspace
和isdigit
函数来判断字符的类型。getchar
函数用于从标准输入读取一个字符。程序使用一个while循环来读取字符,直到遇到换行符(\n)或文件结束符(EOF)。对于每个读取到的字符,程序使用条件语句来判断其类型,并相应地增加对应的计数器。最后,程序输出各种字符的个数。
方法2:
#include "stdio.h"
void main()
{
char c;
int letters=0,space=0,digit=0,others=0;
printf("please input some characters\n");
while((c = getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
digit++;
else
others++;
}
printf("all in all:char=%d space=%d digit=%d others=%d\n",letters,
space,digit,others);
}