c - 我有两个与 getchar() 和 putchar() 有关的问题

标签 c getchar putchar

<分区>

#include<stdio.h>

main()
{
char c;
c=getchar();
putchar(c);

c=getchar();
putchar(c);

c=getchar(); 
putchar(c);

c=getchar();
putchar(c);

c=getchar();
putchar(c);

}

我的第一个问题是,每当我们使用 getchar() 时,它都会在内存中的某处创建一个缓冲区,当我们按下回车键时,getchar() 开始从缓冲区读取内容并且 < strong>getchar() 一次只读取一个字符。所以在上面的程序中,当第一个 getchar() 将执行时,它会在内存中创建一个缓冲区,并且整行内容将存储在缓冲区中假设我在输入 getchar() 时写了“vik” 开始从缓冲区读取内容,然后 'v' 将分配给变量 c,然后只有 'v' 将从缓冲区刷新,因为 getchar() 一次只读取单个字符。然后在下一个语句中 putchar(c) 在屏幕上打印 'v'。所以现在当第二个 getchar() 语句执行时,“ik”留在缓冲区中,它不会再次要求用户写东西,因为除非并且直到缓冲区不会完全刷新它不会再次要求用户写东西写一些东西而不是从缓冲区读取内容。所以这里 "ik"保留在黄油中所以在第二个 getchar() 语句中从缓冲区读取 'i' 然后再次 'i' 将从缓冲区和 putchar(c) 打印“我”。现在,当第 3 个 getchar() 执行它时,'k' 留在缓冲区中,它从缓冲区中读取 'k' 并分配给 c,然后 'k' 也从缓冲区中刷新。此时缓冲区已完全刷新,当第 4 个 getchar() 执行它要求用户写一些东西时,缓冲区中没有内容,因为缓冲区中没有内容,所以假设我写“as”并按回车键。 现在我的主要问题是,当我给出两个内容“as”时,还有两个 getchar() 和 putchar(c) 需要执行,所以为什么只有 'a' 会打印在屏幕上,为什么不打印 's'还有?

而且, 我的第二个问题是,如果我们说当我们使用 getchar() 时,它会在内存中创建一个缓冲区 所以如果我们使用 fflush(stdin) 它必须刷新缓冲区。因此,根据上述程序,当我在第一个 putchar(c) 之后编写 fflush(stdin) 而不是刷新缓冲区时,它会执行并打印与上述程序相同的输出,为什么?

最佳答案

.Now at this point buffer is totally flushed,there is no content is in buffer when 4th getchar() will execute its ask to user to write something because there is no content is in buffer so lets suppose I write "as" and hits enter. Now my main question is that when I give two content "as" and there two getchar() and putchar(c) are left to execute so why only 'a' will print on screen why not 's' also ?

没有。缓冲区中有 \n。这就是为什么您在输入 as 时只得到 a 的原因。

And, My second question is that, if we say that when we use getchar() its create a buffer in memory so if we use fflush(stdin) its have to flush the buffer. So according to this in above program when I write fflush(stdin) after the 1st putchar(c) instead of flushing buffer its executes and print same output as above program why ?

fflush(stdin) 将调用未定义的行为(根据 ANSI C 标准)。你会得到任何东西。你很不幸,它打印了相同的输出。

关于c - 我有两个与 getchar() 和 putchar() 有关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468343/

相关文章:

c - C 中的链表程序错误

c - 无法在 system() 中输入字符串 "echo "$(cat test.txt )""

C 编程 : getchar() won't accept '+' or '-' for input, 但会接受 '*' 和 '/' 吗?

c - 如何创建输入的每个单词以开始新行

c - 使用 getchar() 和 putchar() 复制文件

c - 当用户键入 ./a.out -n 时,我怎么知道 n(正整数)是多少?

c - 如何在用 C 编写的类 FORTH 语言解释器中实现 LOOP

C getchar 与 scanf

在 while 循环中控制 getchar()

c - C 程序中的奇怪输出