Well, you can do it the portable way (there is more than one way to do it the portable way; this is only my latest variation for y'all):
#include <iostream>
#include <limits>
namespace console {
void pause() {
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
}
Or, since all the other things you want to do (like clear the screen) are non-portable anyway, you can do it the Windows way:
#include <iostream>
#include <windows.h>
namespace console {
void pause() {
DWORD mode;
HANDLE hin;
INPUT_RECORD inrec;
DWORD count;
// Instruct the user
std::cout << "Press the 'any' key...";
// Set the console mode to no-echo, raw input,
// and no window or mouse events.
hin = GetStdHandle( STD_INPUT_HANDLE );
GetConsoleMode( hin, &mode );
SetConsoleMode( hin, 0 );
// Wait for and get a single key press
do ReadConsoleInput( hin, &inrec, 1, &count );
while (inrec.EventType != KEY_EVENT);
// Restore the original console mode
SetConsoleMode( hin, mode );
}
}
You can use it the usual way:
int main() {
std::cout << "Hello world!\n" << std::endl;
console::pause();
std::cout << "\n\nThank you!" << std::endl;
return EXIT_SUCCESS;
}
Enjoy!
Reputation Points: 1140
Solved Threads: 229
Postaholic
Offline 2,039 posts
since Oct 2007