Once again: polling input in pure C++ question
Posted: 30 Jun 2006, 09:04
Here is a sample code which should count seconds of runtime, poll stdin from time to time, and do something when user hits the keyboard. It does not work. What is wrong in this code? How to fix it?
Yes, I know about IsPipe(), signal(), kbhit() and bla-bla-bla... (look GreKo's code, I have implemented polling input, and it works).
But is there more elegant, pure C++/stdlib solution of the problem?
Yes, I know about IsPipe(), signal(), kbhit() and bla-bla-bla... (look GreKo's code, I have implemented polling input, and it works).
But is there more elegant, pure C++/stdlib solution of the problem?
- Code: Select all
#include <iostream>
#include <vector>
using namespace std;
#include <time.h>
int main()
{
cout.rdbuf()->pubsetbuf(NULL,0);
cin.rdbuf()->pubsetbuf(NULL,0);
time_t t0 = clock();
long n1 = 0, n2 = 0;
while(1)
{
n1++;
if( n1 < 10000 )
continue;
if( cin.rdbuf()->in_avail() )
{
cout << "Input detected!" << endl;
// Here we should process user input...
// Unfortunately, this code never gets control :((
}
n1 = 0;
if( clock() - t0 > 1000 )
{
n2++;
cout << n2 << "\r";
t0 = clock();
}
}
return 0;
}