Hi,

i have a program that runs a loop during that loop if the user types lets say "status" i want a status report if the user didn't give any input no status report should be displayed

i played around with getline getchar etc but those wait for user input and if no input is given the loop doesn't continue.

can someone point me in the right direction to how i would get this behavior

thanks in advance,
Yrm

WaltP, sorry for the terrible post.

Duoas, thanks i'm on OSX but i need it to work on allot of different OS.
I guess i will just create a status update every minute (which was the original plan).

On POSIX systems, use poll() (or select()) to check to see if there is user input pending.

On Windows systems, use WaitForSingleObject().

I know this example is for windows, but you can easily modify it to work using the POSIX equivalent (Kubuntu update hosed my system and I haven't fixed it yet, so I'm not going to mess with modifying this example today):

#include <iostream>
#include <string>
using namespace std;

#include <windows.h>

int main()
  {
  string s;
  HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );

  cout << "I am going to count to 10.\n"
          "Press ENTER at any time to stop.\n";

  for (unsigned counter = 1; counter <= 10; counter++)
    {
    cout << "\r   \r" << counter << " " << flush;

    // Wait for one second on the standard input.
    // If standard input is waiting, we're done.
    if (WaitForSingleObject( hStdIn, 1000 ) == WAIT_OBJECT_0)
      {
      cout << "\r   \r> ";
      getline( cin, s );
      break;
      }
    }

  if (!s.empty())
    {
    cout << "(You entered \"" << s << "\".)\n";
    }

  cout << "OK. All done.\n";

  return 0;
  }

This kind of "is keypressed" function is easy to do:

#include <windows.h>

bool iskeypressed( int ms )
  {
  return WaitForSingleObject(
    GetStdHandle( STD_INPUT_HANDLE ),
    ms
    );
  }
// POSIX
#define INFINITE (-1)

#include <unistd.h>
#include <poll.h>

bool iskeypressed( int ms )
  {
  struct pollfd pls;
  pls.fd = STDIN_FILENO;
  pls.events = POLLIN | POLLPRI;
  return poll( &pls, 1, ms );
  }

On older BSD systems you may have to use select(), but that is increasingly rare. It isn't any more difficult to use, just a little less friendly.

For the cross-platform part, you'll just need your build environment to compile the appropriate OS-specific file (which defines these functions).

The nice thing here is that these functions do not lock the machine into a processor loop, but yield to other processes while the timeout (which is the 'ms' argument to my functions above) is not zero.

Example of use:

cout << "Press ENTER to quit.." << flush;
iskeypressed( INFINITE );
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );

Hope this helps.

Edited 6 Years Ago by Duoas: n/a

Comments
thanks for the great info
This question has already been answered. Start a new discussion instead.