in_avail() not working for me.

I am using windows. I copied this program from Reference section in this site, as it is.When I run the program it always shows 0 additional characters, no matter what.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main () {

  streamsize size;
  char ch;

  streambuf * pbuf;
  pbuf = cin.rdbuf();

  cout << "Please enter some characters: ";
  cin >> ch;

  size = pbuf->in_avail();

  cout << "The first character you entered is: " << ch << endl;
  cout << size << " additional characters in input buffer" << endl;

  return 0;
}
The effect of in_avail() is entirely implementation-defined. In particular, In many C++ implementations (likely including yours), std::cin has no buffer by default, so in_avail() always returns zero.

If you're using gcc, add the line

cin.sync_with_stdio(false);

somewhere near the beginning of main. That turns on cin's buffer in GNU library (but, for example, in LLVM library, you'd still have zero buffer)
Last edited on
Thanks so much Cubbi. I added the line cin.sync_with_stdio(false); and it worked. The only problem is that it returns one more than the actual no. of additional characters.

Although I can manage it by manually subtracting 1 from returned value, I was curious why would the function do so.
Topic archived. No new replies allowed.