在代码中,为什么使用 fflush 修复输出?

In the code,why using fflush fixes the output?

我创建了一个堆栈来解决问题。这是插入函数:

insert()
{
    char data;
    scanf("%c",&data);
    struct node* newNode=create_node(data);//creates a new node
    if(head==NULL)
    {
        head=newNode;
        tail=head;
        return;

    }
    newNode->next=head;
    head=newNode;
    return;

现在,我尝试像这样在堆栈中压入一些元素,

main()
{
    char input[20];
    insert();
    insert();
    insert();
    insert();
    insert();
    print();
}

但是我注意到在每个 insert 之后的 insert 是 skipped.So 它只需要 3 输入时我应该采用 5..i.e., 我在采用 3 个输入后给出输出。

我能够通过在插入函数中添加 fflush 来解决问题。

我想知道到底发生了什么导致了这个.. 这是否意味着我们不能像我那样接受输入?

替换

scanf("%c", &data); 

scanf(" %c", &data); 

解决问题。 %c 后面的 space 字符将跳过所有白色 space 字符,包括 none,直到 C11 标准中指定的第一个非白色 space 字符:

7.21.6.2 The fscanf function

[...]

  1. A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails

你的程序只接受 3 个输入而不是 5 个输入的原因是标准输入流 (stdin) 中有一个换行符 (\n)。还记得在为 scanf 输入数据后按 Enter 吗?这个字符(换行符或\n)是不是被这个scanf捕获的。该字符在下次调用时由 scanf%c 捕获。这就是 scanf 不等待进一步输入并“跳过”某些输入的原因。

函数 fflush,当与 stdin 一起使用时, 可能 某些 实现中工作,尽管行为据说是未定义的标准:

7.21.5.2 The fflush function

[...]

  1. If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.