【思路】这是一个关于字符处理的问题,首先可以定义一个字符变量ch,利用getchar()函数把用户从键盘输入的字符逐个接收,存储在ch中,然后对 ch进行判断分类。当读取的字符不是换行符时重复执行循环体,直到遇到换行符为止。while语句的条件表达式可以 写成"ch!='\n'"。
【程序代码如下】
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char ch;
int letter = 0,digital = 0,space = 0,other = 0;
while((ch = getchar())!= '\n') //接收从键盘输入的字符,并判断是否为换行符,遇到换行符则停止循环。
{
if( ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' ) //判断是否为字母
letter++;
else if(ch >= '0' && ch <= '9' ) //判断是否为数字
digital++;
else if(ch == ' ')
space++; //判断是否为空格
else
other++;
}
printf("字母=%d,数字=%d,空格=%d,其它字符=%d\n",letter,digital,space,other);
return 0;
}
【运行结果如下】