统计字符个数

//各类字符统计
#include <stdio.h>
/*测试用的	
	//输入
	c = getchar();
	while(c!='\n'){
		c = getchar();
	
		printf("%c", c);		
	} 
*/
int main()
{
	
	char c;
	int letter = 0;
	int number = 0;
	int space = 0;
	int other = 0;
	
	c = getchar();
	//循环判断 
	while(c!='\n'){
		//判断字符
		if(c>='a'&&c<='z' || c>='A'&&c<='Z'){
			letter++;
		}else if(c>='0'&&c<='9'){
			number++;
		}else if(c==' '){
			space++;
		}else{
			other++;
		}
		c = getchar();	
	} 

	//打印所求 
	printf("字母=%d,数字=%d,空格=%d,其他=%d\n", letter, number, space, other); 
	
	return 0;
} 

学习到:

  1. getchar()函数的使用
    读取一个字符并输出,直到文件结束EOF(end of file)
    缓冲区的存在:
    从键盘键入的字符都先到缓冲区中,然后getchar函数从缓冲区读取字符然后输出,如果缓冲区还有字符需再一个getchar函数才能继续读取字符,总之一个getchar读取一个字符,想要把缓冲区字符读完,则需要对应个数的getchar函数。
    注意!!:换行符也会被getchar函数读取
  2. 多个字符读入
    while()+getchar()且循环截止条件是 ch!='\n'
posted @ 2022-10-22 18:25  行至为成  阅读(210)  评论(0)    收藏  举报