Greetings,
I am trying to determine if there is input on the console without blocking.
I have built a simple console app in VC++ .NET1.1/MSDE 2003.
I would think that after typing in some characters and a carriage return, it would return those characters one at a time. Instead, it doesn't appear that the in_avail() call ever returns anything but 0.
Here is the code:
#include
"stdafx.h"#include
<iostream>// just trying to have a nonblocking way to see if there is any input on the console
// hmmm. how come this don't work
int
_tmain(int argc, _TCHAR* argv[]){
using
namespace std; while (true) { if ( (cin.rdbuf( )->in_avail( )) > 0) { char c;cin >> c;
printf("found character %c\n",c);
}
}
return 0;}
thanks,
Jim

cin.rdbuf()->in_avail() always returning zero?
pfongkye
The reason is because rdbuff() is a method to access the streambuf* member of cin which is a istream object. You havent read anything in yet so in_avail() returns zero when you call it.
Regards
Sahir
tedh
jf3
int a;
streambuf* sb;
sb = cin.rdbuf();
cout<<sb->in_avail()<<endl; // will print zero
cin>>a;
sb = cin.rdbuf();
cout<<sb->in_avail()<<endl; // will print 1
It does not matter if you have typed something in. If cin's streambuf is empty sb->in_avail() will return 0.
Regards
Sahir
George1905
Um! Since I am not sure if this is someone's homework I won't post the code. You need to declare a reasonably sized buffer (say char buff[255]) to hold the input, then inside your infinite loop you need to use cin.getline(buff, sizeof(buff));and then iterate through buff to print one char after another. When you hit '\0' or reach the 254th element you exit the for loop. Then you need to find some way to allow the user to exit the program. So you got to break out of the infinite loop when the user enters a terminate command e.g. "QUIT".
Regards
Sahir
Alexey Rokhin
Sahir,
Thank you.
It is returning zero even after I type in some characters at the command line and hit carriage return.
If I use a get() or something like that, it will block waiting for input, right
cheers,
Jim