while((c=getchar())!=EOF)

来源:互联网 发布:seo常见问题 编辑:程序博客网 时间:2024/05/15 23:52
#include<stdio.h> 
int main()
{
int c;
printf("input a character:");
while((c=getchar())!=EOF)

if (c<32)
printf("This is a control character\n");
else if (c>='0'&&c<='9') 
printf("This is a digit\n"); 
else if (c>='a'&&c<='z')
printf("This is a small letter\n"); 
else 
printf("This is another character\n");
}
}
运行起来如图:,每次输入会连同enter键一起输入,貌似是因为Enter也是一个输入字符,但是如果运行
#include<stdio.h>
int main()
{
char c; 
while((c=getchar())!=EOF) 
putchar(c);
}

似乎enter对其没什么影响。

-----------------------------------------------------------------------------------------------------------------------------------

第一例:可以在while循环块结尾加一句while(getchar()!=‘\n');使得计算机忽略当前行其他的字符,包括回车,以达到去除enter对其的影响。


第二例:在第二个例子中,enter键貌似没影响,不过,实际上依然是“有影响的”。
因为putchar()在输出我输入的字符后,自动换行了。即将我输入的回车也一同输出了。
这是由于getchar(),会完整地读入所有字符。
而我使用的是一个循环控制,所以我所输入的所有字符都会被接收到,直到函数判断到了文件末尾EOF。


在内部实现上,getchar()调用了fgetchar(),而fgetchar()又使用了getc(stdin)。
所以最终效果上相当于getchar()使用了宏getc(stdin)。


原创粉丝点击