getchar有一个int型的返回值.
当程序调用getchar时.
程序就等着用户按键.
用户输入的字符被存放在键盘缓冲区中.
直到用户按回车为止(回车字符也放在缓冲区中).
当用户键入回车之后,getchar才开始从stdio流中每次读入一个字符.
getchar函数的返回值是用户输入的第一个字符的ASCII码,如出错返回-1,
且将用户输入的字符回显到屏幕.
如用户在按回车之前输入了不止一个字符,
其他字符会保留在键盘缓存区中,等待后续getchar调用读取.
也就是说,后续的getchar调用不会等待用户按键,
而直接读取缓冲区中的字符,
直到缓冲区中的字符读完为后,才等待用户按键.
注意小细节。
#include<stdio.h>
int main()
{
char c;
int letters=0,spaces=0,digits=0,others=0;
printf("输入随意的字符串:\n");
while((c=getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
{
letters++;//记录字母
}
else if(c>='0'&&c<='9')
{
digits++;//记录数字
}
else if(c==' ')
{
spaces++;//记录空格
}
else
{
others++;
}
}
printf("字母=%d,数字=%d,空格=%d,其他=%d\n",letters,digits,spaces,others);
return 0;
}