Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does in_avail() output zero even if the stream has some char?

Tags:

c++

#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

I think this will output 0 and 2

but when I run the code, it output 0 and 0, why?

or if I change cin.putback(1); to int a; cin >> a; with input 12 12;

it still outputs 0 and 0

like image 505
miskcoo Avatar asked Jul 04 '13 15:07

miskcoo


2 Answers

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'

like image 92
MadOgre Avatar answered Oct 21 '22 11:10

MadOgre


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.

like image 45
CB Bailey Avatar answered Oct 21 '22 09:10

CB Bailey