c - 了解 putchar 循环

标签 c

此代码需要多个 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/

相关文章:

c - 在 C 中发出信号和使用处理程序

c - 需要使用 c 为错误处理提供超时

c - C 中的图形程序

c++ - CS高级项目思路涉及Unix系统编程

c++ - 我如何运行 GDB,在命令行中输入文本并查看可执行文件如何处理这些条目?

c - 为什么转换这个指针也会改变指向的值

c - scanf GCC for long double

c - 跟踪链表的初始值

c - 分析由 Ruby 程序调用的 C 共享库

c - Xv6 中的 Omode 是什么?