getchar是读入函数的一种。它从标准输入里读取下一个字符,相当于getc(stdin)。返回类型为int型,为用户输入的ASCII码或EOF。
函数内容
int getchar(void)
{
static char buf[BUFSIZ];
static char* bb=buf;
static int n=0;
if(n==0)
{
n=read(0,buf,BUFSIZ);
bb=buf;
}
return(--n>=0)?(unsigned char)*bb++:EOF;
}
用法
该函数声明在 stdio.h 头文件中,使用的时候要包含stdio.h头文件。如#include<stdio.h>
int getchar(void);
注解
getchar
getchar由宏实现:#define getchar() getc(stdin)。getchar有一个int型的返回值。当程序调用getchar时.程序就等着用户按键。用户输入的
字符被存放在键盘
缓冲区中。直到用户按回车为止(回车字符也放在缓冲区中)。当用户键入回车之后,getchar才开始从stdio流中每次读入一个字符。getchar函数的返回值是用户输入的字符的ASCII码,若文件结尾(End-Of-File)则返回-1(EOF),且将用户输入的字符
回显到屏幕。如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取。也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完后,才等待用户按键。
程序举例
#include<stdio.h>
#include<conio.h>
main(void)
{
int c;
int a;
a=getchar();
if (EOF!=a)
printf("%c",a);
while((c=getchar())!='\n')//c接收的值是输入第一个字符后按下的回车换行符'\n',c是不会显示的
{
if (EOF==a)
break;
printf("%d",c);
}
getchar();
}
/*getchar()-Note that getchar reads from stdin and is line buffered;
this means it will not return until you press ENTER. */
注:可以利用getchar()函数让程序调试运行结束后等待编程者按下键盘才返回编辑界面,用法:在主函数结尾,return 0;之前加上getchar();当你getchar()前没有使用回车的话可以用这个函数让程序调试运行结束后等待编程者按下键盘才返回编辑界面,否则将直接返回编辑界面;如:
#include<stdio.h>
int main(void)
{
int i ;
scanf("%d",&i);
getchar();
/*当此处用这个函数时,当你输入函数并且回车的话将直接以迅雷不及掩耳之势完成函数的操作*/
}