getchar函数

C 库函数 int getchar(void) 从标准输入 stdin 获取一个字符(一个无符号字符)。这等同于 getc 带有 stdin 作为参数。

下面实例展示具体用法

#include <stdio.h>

int main ()
{
   char c;
 
   printf("请输入字符:");
   c = getchar();
 
   printf("输入的字符:");
   putchar(c);

   return(0);
}

由于只能获取一个字符,故只获取r;

 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

 程序分析:利用while语句,条件为输入的字符不为'\n'。

/* 输入一些字符,判断字母,数字,空格和其他类型的个数*/
#include<stdio.h> int main(){ char c; int letters=0,numbers=0,spaces=0,others=0; //初始化为0 printf("请输入一些字符:"); while((c=getchar())!='\n'){ if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) letters++; else if(c>='0'&&c<='9') numbers++; else if(c==' ') spaces++; else others++; } printf("字母=%d,数字=%d,空格=%d,其他=%d\n",letters,numbers,spaces,others); }

 

 

posted @ 2019-07-21 18:45  acehm  阅读(683)  评论(0编辑  收藏  举报