反正在标准输入缓冲区偷看? [英] Is there anyway to peek at the stdin buffer?
问题描述
我们知道,标准输入
,默认情况下,缓冲输入;那证明是在任何关于标准输入
是假数据的机制,如 scanf函数的使用()
:
INT的main()
{
焦C [10] = {'\\ 0'};
scanf函数(%9,C);
的printf(%s,而左边是数:%d \\ n,C的getchar());
返回0;
}
./ a.out的
结果打招呼
结果打招呼,左边是10
块引用>
10
当然是换行...我一直很好奇,反正是有窥视在
标准输入
缓冲不删除任何可能存在呢?修改
结果一个更好的例子可能是:scanf函数(%9 [^],C);
随着at.ct的输入,现在我的数据(
CT \\ n
)留在标准输入
,而不仅仅是一个换行符。解决方案可移植的,你可以用
的getchar()
得到输入流中的下一个字符,然后将其推回来与ungetc()
,这会导致一个状态,好象字符没有从流中除去。
的
与ungetc
函数把由指定的字符c
(转换为unsigned char型
)返回到输入流通过流指向。推回字符将在他们的推动相反的顺序在该流后续读取返回。
块引用>只有推回一个字符是由标准的保证,但通常情况下,你可以推回了。
正如在其他的答案RESP提及。还有的意见,在实践中,你几乎可以肯定在缓冲区偷看,如果你提供自己的缓冲区
setvbuf用来
,尽管这并非没有问题:
如果
BUF
不是空指针,它指向可以用来代替由setvbuf用来$ C分配的缓冲区的数组$ C>函数
块引用>这留下所提供的缓冲器可能不会在所有被使用的可能性。
所述阵列的在任何时间的内容是不确定的。
块引用>这意味着你不能保证该缓冲区的内容反映了实际输入(它使得使用缓冲区未定义的行为,如果它具有自动存储时间,如果我们挑剔)。
然而,在实践中的主要问题将被找出其中的缓冲缓冲输入的的尚未消耗掉的部分开始以及在哪里结束。
We know that
stdin
is, by default, a buffered input; the proof of that is in usage of any of the mechanisms that "leave data" onstdin
, such asscanf()
: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
being newline of course...I've always been curious, is there anyway to "peek" at the
stdin
buffer without removing whatever may reside there?EDIT
A better example might be:scanf("%9[^.]", c);
With an input of "at.ct", now I have "data" (
ct\n
) left onstdin
, not just a newline.解决方案Portably, you can get the next character in the input stream with
getchar()
and then push it back withungetc()
, which results in a state as if the character wasn't removed from the stream.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.Only one character of pushback is guaranteed by the standard, but usually, you can push back more.
As mentioned in the other answers resp. the comments there, in practice, you can almost certainly peek at the buffer if you provide your own buffer with
setvbuf
, although that is not without problems:If
buf
is not a null pointer, the array it points to may be used instead of a buffer allocated by thesetvbuf
functionthat leaves the possibility that the provided buffer may not be used at all.
The contents of the array at any time are indeterminate.
that means you have no guarantee that the contents of the buffer reflects the actual input (and it makes using the buffer undefined behaviour if it has automatic storage duration, if we're picky).
However, in practice the principal problem would be finding out where in the buffer the not-yet-consumed part of the buffered input begins and where it ends.
这篇关于反正在标准输入缓冲区偷看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!