题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为'\n'。
涉及到的知识点:
1.getchar()作用:
函数从键盘上读入一个字符,并显示该字符(回显)【敲什么屏幕上显示什么】。
但是当你用printf进行输出的话只会显示第一个字符。
- 例子:
#include<stdio.h>
int main()
{
char c;
c = getchar();
printf("%c", c);
}
- so why?这涉及到缓 冲 区。
- 输入:非缓冲输入和缓冲输入。
非缓冲输入:输入字符的立即回显(输入的内容对程序立即可用)。
缓冲输入:输入的字符被收集并储存在一个被称为缓冲区的临时存储区域中。当按下回车键时,使所键入的字符块对程序变为可用。
缓冲:完全缓冲和行缓冲
完全缓冲:缓冲区满时被清空(文件输入)。
行缓冲:遇到一个换行字符时将被清空缓冲区(键盘输入时,按下回车键将清空缓冲区)
- 所以说我的理解是:当把一堆字符输入到电脑中后,这堆字符便存储在缓冲区中,一旦调用getchar函数,缓冲区将最先读取先存储的字符,并且释放掉,所以“I love you."中只读取了一个字符I,并且释放掉,其余字符仍旧在缓冲区中,未被读取。
C练习实例 17
#include<stdio.h>
int main()
{
printf("please input some characters:\n");
char c;
int letters = 0, space = 0, digits = 0, others = 0;
while((c=getchar())!= '\n' )
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
letters++;
else if (c == ' ')
space++;
else if (c >= '0' && c <= '9')
digits++;
else
others++;
}
printf("letters=%d,space=%d,digit=%d,others=%d", letters, space, digits, others);
}
错误实例1:
#include<stdio.h> int main() { printf("please input some characters:\n"); char c = getchar();//xxx wrong int letters = 0, space = 0, digits = 0, others = 0; while ((c=getchar())!= '\n') { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) letters++; else if (c == ' ') space++; else if (c >= '0' && c <= '9') digits++; else others++; } printf("letters=%d,space=%d,digit=%d,others=%d", letters, space, digits, others); }
letters的数量为7而不是8
so why?
根据前面缓冲区的知识点,第五行代码char c = getchar();与第八行代码while ((c=getchar())!= '\n')有矛盾。char c = getchar()读取了‘I’并且释放掉,接着while ((c=getchar())!= '\n')就会从‘ ’(空格)读取,落掉了'I',导致letters少计一个数。
错误实例2:
#include<stdio.h>
int main()
{
printf("please input some characters:\n");
char c = getchar();//xxx wrong
int letters = 0, space = 0, digits = 0, others = 0;
while (c!= '\n')//xxx wrong
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
letters++;
else if (c == ' ')
space++;
else if (c >= '0' && c <= '9')
digits++;
else
others++;
}
printf("letters=%d,space=%d,digit=%d,others=%d", letters, space, digits, others);
}
运行不出来orz...
同理, 第五行代码char c = getchar();只是在重复读取I,所以在debug过程中,letters不断计数,导致程序跑不出来==
综上,
当遇到while((ch=getchar())!='\n')的情况,这里的意思是在缓冲区中遇到‘\n’就结束循环。读取一个字符,该字符就被释放掉,达到一个循环的效果。
参考:
原文链接:https://blog.csdn.net/gxyqn626/article/details/79253238