C getchar() 和 putchar()
通过 K&R,我试图了解 C。 我想编写一个程序,在屏幕上打印用户的上一行,除非该字符是“a”。
int main(){
int c;
while((c=getchar())!=EOF){
if(c!='a')
putchar(c);
}
return 0;
}
是的,节目不多。但它不会按预期工作。我是否需要使用字符“a”的ASCII值,因为上面的代码只是打印所有字母,无论是否是a。
Going through K&R, I'm trying to get my head around C.
I want to write a program that prints on the screen the user's previous line, unless the character was "a".
int main(){
int c;
while((c=getchar())!=EOF){
if(c!='a')
putchar(c);
}
return 0;
}
Yes, the program isn't much. But it won't work as intended. Do I need to use the ASCII value of the character "a", because the above code just prints all the letters regardless of being a or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码应该按照指定的方式工作,但是您会发现,在 while 循环中使用
getchar
将在输入 a 时打印回车符。这是因为在当前的实现中getchar
将继续读取输入缓冲区直到它为空,如果您想阻止这种情况发生,您可以在 if 语句中刷新它。此时输入一串文本将打印该字符串,删除任何 *a*s
The code should work as specified, but what you will find is that using
getchar
with the while loop will print a carriage return when a is entered. This is because in the current implementationgetchar
will keep reading the input buffer till it is empty, if you wanted to stop this happening you could flush it in the if statement.Entering a string of text at the moment will print the string removing any *a*s