Making a program wait until a key is pressed..

I know this is already explained in the sticky, but I have to use it multiple times in my program, sometimes to wait for the user to press some key before continuing the program. I had a function like this:

1
2
3
4
5
void wait()
{
    cout<<"Press ENTER to continue....."<<endl<<endl;
    cin.ignore(1);
}

Which works sometimes and doesnt work some other times. So how exactly can I code a function which (sucessfully) waits for the user to press some key (Enter?) before moving on with the program?

PS:Offtopic perhaps, but anyone know where I can find some decent text-based RPG tutorials? I'm halfway through mine and my code's starting to look ugly..
Last edited on
you can use kbhit() (stands for keyboardhit)

1
2
3
4
#include <windows.h>

while (!kbhit);
 char dummy = getch();


int main
I suppose I should add an addendum to the sticky that lists all these things for people in discrete chunks.

Using the Win32 API:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <windows.h>

TCHAR pressanykey( const TCHAR* prompt = NULL )
  {
  TCHAR  ch;
  DWORD  mode;
  DWORD  count;
  HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );

  // Prompt the user
  if (prompt == NULL) prompt = TEXT( "Press any key to continue..." );
  WriteConsole(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    prompt,
    lstrlen( prompt ),
    &count,
    NULL
    );

  // Switch to raw mode
  GetConsoleMode( hstdin, &mode );
  SetConsoleMode( hstdin, 0 );

  // Wait for the user's response
  WaitForSingleObject( hstdin, INFINITE );

  // Read the (single) key pressed
  ReadConsole( hstdin, &ch, 1, &count, NULL );

  // Restore the console to its previous state
  SetConsoleMode( hstdin, mode );

  // Return the key code
  return ch;
  }

Now your wait() function can just pass-off to the pressanykey() function:
1
2
3
4
inline void wait()
  {
  pressanykey();
  }


One of the unfortunate errors in the design of C++ I/O streams is that it takes extra pains to completely divorce itself from the underlying device(s). Hence, using the standard streams to handle these kind of things is a bit tricky. The above is for Win32. If you want to do the same for POSIX systems (Linux, etc), here is how to do the exact same thing:
http://www.cplusplus.com/forum/beginner/1988/page4.html#msg14522
(But be warned, on POSIX systems if the user presses some oddball key like any of the arrow keys or a function key of some kind, you may not get the entire character sequence. --This is something I need to address also.)

You will notice that the two are prototyped slightly differently. Personally, I would adjust them to match if I planned to do any cross-platform programming. In any case, adjust them however suits you best.

If you want to stay strictly C++, the only surely safe way to do it is:
1
2
3
4
5
6
7
8
#include <iostream>
#include <limits>

void wait()
  {
  std::cout << "Press ENTER to continue...";
  std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
  }

In all of these examples, however, it is a precondition that the input is at an appropriate read state. If you use something like cin >> my_int; before you use any of them, that extraneous newline will still be sitting in the input buffer waiting to be picked up by the pause functions.

And again, it is unfortunate that there is no standard way to discard all unread input. You will have to use some platform-specific way to forcibly sync the input to what the user next types. On Windows, the function is
BOOL FlushConsoleInputBuffer( HANDLE hConsoleInput )
It is a little trickier on POSIX, but just about as simple. (I don't remember exactly how to do it right now... and my fingers are tired of this post... so I'll address it later in my addendum-to-be.)

Phew. Hope this helps.

Oh yeah, int main's method will work just fine on Windows. I don't know of any well-known Windows compiler (within the last ten years) that doesn't support it. But the file to #include is <conio.h> --kbhit() and getch() are not part of the Win32 API.
Ah, thanks you two I'll check both of them out, although for some bizarre reason I feel uncomfortable #including windows.h

But thanks anyway, I'll give both of them a try.

Edit:
I just stumbled across this in Wikipedia
http://en.wikipedia.org/wiki/Ncurses

Now, I dont know much C++, but the definitions of both ncurses and conio seem similar (ie, both are used to create text user interfaces). I saw someone using it to clear the screen some where (probably here). I'm just wondering if this library would have "something" to pause execution of the the program..

Edit2:
Apparently its not available for windows.
Last edited on
It does, and it is. :-)

PDCurses
Win32, DOS, OS/2, Plan 9, etc.
http://pdcurses.sourceforge.net/

Enjoy!

BTW, are you the same Poke that did those awesome "matryoshvstanka" over at BA?
Last edited on
Oh. So would the curses library help me in anyway with my problem?

And I just googled "matryoshvstanka" so no I didnt do that. Its kind of cool though. My "Poke" is pronounced "Pokey" and his is pronounced the usual way (probably) :P I know its unnecessary, but whatever.
Wow, I can hardly believe how many times I have linked this post just in the past 18 hours... (Sorry, I should have linked it for you already):
http://www.cplusplus.com/forum/beginner/4520/page1.html#msg19965

I figured it was a long-shot, seeing as you are 386? :-P

But yeah, it should do all the console stuff you want. If you want to get into graphics you should check out SDL or OpenGL or Ogre3D or somesuch, and use the input routines provided by that library.

:-)
Ah thanks a lot, I've added Curses into my to-learn list. I plan to use SDL for graphics (I'm a very long way off from starting though) seeing as people seem to say its cross-platform and most importantly, easier to learn.
If anyone's like me and had no idea how to install/compile/use a library, head over to: http://in.youtube.com/watch?v=mYnfix8ruAo

God I love the internet.
Topic archived. No new replies allowed.