输入一行字符,分别统计出其中英文字母,空格,数字和其它字符的个数。麻烦讲解仔细一点,谢谢
#include <stdio.h>
int main()
{
char c;
int letters = 0, space = 0,digit = 0,other = 0;
printf("请输入一行字符:");
while ((c=getchar())!='\n')
{
if (c >= 'a' && c <= 'z' || c >= 'A'&&c <= 'Z') // 字母就 +1
letters++;
else if (c == ' ')
space++;
else if (c >= '0'&&c <= '9')
digit++;
else
other++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",letters,space,digit,other);
return 0;
}
用<ctype.h>
头文件下的isalpha(int c) isdigit(int c) isspace(int c)
以及一个else
子句更方便,更快速哦
#include<stdio.h>
#include<ctype.h>
int main(){
char c;
int box[4] = {0,0,0,0};
while((c=getchar())!='\n'){
if(isalpha(c)) box[0]++;
else if(isspace(c)) box[1]++;
else if(isdigit(c)) box[2]++;
else box[3]++;
}
printf("字母:%d 空格:%d 数字:%d 其他:%d",box[0],box[1],box[2],box[3]);
return 0;
}