有什么办法可以窥视标准输入缓冲区吗? [英] Is there any way to peek at the stdin buffer?

查看:112
本文介绍了有什么办法可以窥视标准输入缓冲区吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道 stdin 默认情况下是一个缓冲输入;证明是使用了在 stdin 上保留数据的任何机制,例如 scanf()

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" on stdin, such as scanf():

int main()
{
    char c[10] = {'\0'};
    scanf("%9s", c);
    printf("%s, and left is: %d\n", c, getchar());
    return 0;
}




./ a.out

你好

你好,左边是10

./a.out
hello
hello, and left is 10

10 当然是换行符...

10 being newline of course...

我一直很好奇,有什么办法可以窥视 stdin 缓冲区而不会删除可能存在的任何内容?

I've always been curious, is there any way to "peek" at the stdin buffer without removing whatever may reside there?

编辑

一个更好的示例可能是:

EDIT
A better example might be:

scanf("%9[^.]", c);

输入 at.ct,现在我得到数据( ct\n )留在 stdin 上,而不仅仅是换行符。

With an input of "at.ct", now I have "data" (ct\n) left on stdin, not just a newline.

推荐答案

您可以使用 getchar(),然后使用 ungetc()将其推回原位,这将导致一个状态,就好像字符没有从流中删除。

Portably, you can get the next character in the input stream with getchar() and then push it back with ungetc(), which results in a state as if the character wasn't removed from the stream.


ungetc 函数推送由 c (转换为 unsigned char )返回到流指向的输入流。推回字符将由其后按其推压相反的顺序在该流上的后续读取返回。

The ungetc function pushes the character specified by c (converted to an unsigned 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.

只有一个推回字符是

如其他答案所述。实际上,如果您为自己的缓冲区提供 setvbuf ,您几乎可以肯定地看到缓冲区,尽管那并非没有问题:

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:


如果 buf 不是空指针,则可以使用它指向的数组代替分配的缓冲区通过 setvbuf 函数

If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function

可以避免提供的缓冲区


数组的内容在任何时候都是不确定的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆