为什么即使流中有一些char,in_avail()也输出零? [英] Why does in_avail() output zero even if the stream has some char?
问题描述
#include <iostream>
int main( )
{
using namespace std;
cout << cin.rdbuf()->in_avail() << endl;
cin.putback(1);
cin.putback(1);
cout << cin.rdbuf()->in_avail() << endl;
return 0;
} //compile by g++-4.8.1
我认为这将输出0并2
I think this will output 0 and 2
但是当我运行代码时,它输出0和0,为什么?
but when I run the code, it output 0 and 0, why?
cin.putback(1);诠释cin >> a;输入12 12;
or if I change cin.putback(1); to int a; cin >> a; with input 12 12;
它仍然输出0和0
推荐答案
必须发生的是,您的 putback
在 streambuf
获取与<$相关的区域中未找到任何房间c $ c> std :: cin (否则将有一个读取位置,而 egptr()-gptr()
将不可用)零),并且必须通过 pbackfail
进入基础层。
What must have happened is that your putback
didn't find any room in the streambuf
get area associated with std::cin
(otherwise a read position would have been available and egptr() - gptr()
would have been non-zero) and must have gone to an underlying layer thanks to pbackfail
.
in_avail( )
将调用 showmanyc()
,并且返回零(这是该虚拟函数的默认实现)是安全的,因为这意味着读取可能会阻塞,并且可能会失败,但不能保证两者都执行。显然,在这种情况下,实现可以为 showmanyc()
提供更有用的实现,但是简单的实现便宜且符合要求。
in_avail()
will call showmanyc()
and zero (which is the default implementation of this virtual function) is a safe thing to return as it means that a read might block and it might fail but isn't guaranteed to do either. Obviously it is possible for an implementation to provide a more helpful implementation for showmanyc()
in this case, but the simple implementation is cheap and conformant.
这篇关于为什么即使流中有一些char,in_avail()也输出零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!