我们知道 stdin
默认情况下是一个缓冲输入;证明是使用任何在 stdin
上“留下数据”的机制,例如 scanf()
:
int main()
{
char c[10] = {'\0'};
scanf("%9s", c);
printf("%s, and left is: %d\n", c, getchar());
return 0;
}
./a.out
hello
hello, and left is 10
10
当然是换行...
我一直很好奇,有没有什么方法可以“窥视”stdin
缓冲区而不删除那里可能存在的任何内容?
编辑
一个更好的例子可能是:
scanf("%9[^.]", c);
输入“at.ct”后,现在我在 stdin
上留下了“数据”(ct\n
),而不仅仅是一个换行符。
最佳答案
可移植性地,您可以使用 getchar()
获取输入流中的下一个字符,然后使用 ungetc()
将其推回,这会导致一种状态该角色未从流中删除。
The
ungetc
function pushes the character specified byc
(converted to anunsigned char
) back onto the input stream pointed to by stream. Pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing.
标准只保证一个字符的pushback,但通常情况下,你可以pushback更多。
如其他答案中所述。实际上,如果您使用 setvbuf
提供自己的缓冲区,您几乎肯定可以查看缓冲区,尽管这并非没有问题:
If
buf
is not a null pointer, the array it points to may be used instead of a buffer allocated by thesetvbuf
function
这留下了可能根本不使用提供的缓冲区的可能性。
The contents of the array at any time are indeterminate.
这意味着您无法保证缓冲区的内容反射(reflect)了实际输入(如果我们挑剔的话,如果它具有自动存储持续时间,它会导致使用缓冲区未定义的行为)。
然而,在实践中,主要问题是找出缓冲区中缓冲输入中尚未使用的部分的开始位置和结束位置。
关于c - 有什么办法可以查看 stdin 缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993742/