此代码需要多个 f
并仅打印 1。有人可以向我解释一下为什么此代码不打印两个 f
吗? putchar
出现两次,但没有 EOF
。我已经盯着它看了好几个小时了,但我不明白它如何只打印 1 f
。
代码运行正常。我只是不明白它是如何一步一步工作的。
/* A program that takes input of varied 'f's and out puts 1 f */
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF)
{
if (c == 'f')
{
putchar(c);
}
while (c == 'f')
{
c = getchar();
}
if (c != EOF) putchar(c);
}
}
谢谢
最佳答案
我将逐步在代码中添加注释;对于 f
(或实际上 f\n
)作为输入:
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) // You type f and hit return key (remember this)
{
if (c == 'f') // c contains 'f' is true
{
putchar(c); // print 'f'
}
while (c == 'f') // c == 'f' is true
{
c = getchar(); // '\n' is buffered on stdin from return key
// so getchar() returns '\n'. So c will be set to '\n'
// It goes back to the while loop and checks if c == 'f'
// but it's not, it's '\n'! So this will run once only.
}
if (c != EOF) putchar(c); // '\n' != EOF, so print '\n' newline, back to loop
}
}
因此将 f\n
作为输入将产生输出 f\n
在输入fffff
的情况下(实际上是fffff\n
),如下:
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) // You type fffff and hit return key
{
if (c == 'f') // c contains 'f' is true, first 'f'
{
putchar(c); // print 'f'
}
while (c == 'f') // First loop, c == 'f'
// Second loop, c == 'f'
// Last loop, c == '\n', so false
{
c = getchar(); // First loop: 'ffff\n' is still buffered on stdin
// c = 'f', loop again
// Last loop: c = '\n'
}
if (c != EOF) putchar(c); // '\n' != EOF, so print '\n' newline, back to loop
}
}
你会看到你的内部 while
循环会吃掉所有的 f
直到你点击 \n
,因此与上面的效果相同。
关于c - 了解 putchar 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152595/