8
#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

但是当我运行代码时,它输出0和0,为什么?

或者如果我改变 cin.putback(1); 到int a;辛 >> 一; 输入 12 12;

它仍然输出 0 和 0

4

2 回答 2

7

Apparently it's a bug/feature of some compiler implementations Insert the line

cin.sync_with_stdio(false);

somewhere near the beginning of code, and that should fix it

EDIT: Also remember that in_avail will always return 1 more than the number of chars in the input because it counts the end of input character.

EDIT2: Also as I just checked, putback does not work unless you have attempted to read something from the stream first, hence the "back" in "putback". If you want to insert characters into the cin, this thread will provide the answer: Injecting string to 'cin'

于 2015-03-25T17:06:08.767 回答
2

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() 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.

于 2013-07-04T16:27:07.813 回答