View Single Post
Join Date: Oct 2007
Posts: 1,951
Reputation: Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of 
Solved Threads: 214
Featured Poster
Duoas's Avatar
Duoas Duoas is offline Offline
Posting Virtuoso

Re: Replacing system("pause"); with a function

 
0
  #13
Jan 14th, 2008
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):
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. namespace console {
  5. void pause() {
  6. std::cout << "Press ENTER to continue...";
  7. std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
  8. }
  9. }

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:
  1. #include <iostream>
  2. #include <windows.h>
  3.  
  4. namespace console {
  5. void pause() {
  6. DWORD mode;
  7. HANDLE hin;
  8. INPUT_RECORD inrec;
  9. DWORD count;
  10.  
  11. // Instruct the user
  12. std::cout << "Press the 'any' key...";
  13.  
  14. // Set the console mode to no-echo, raw input,
  15. // and no window or mouse events.
  16. hin = GetStdHandle( STD_INPUT_HANDLE );
  17. GetConsoleMode( hin, &mode );
  18. SetConsoleMode( hin, 0 );
  19.  
  20. // Wait for and get a single key press
  21. do ReadConsoleInput( hin, &inrec, 1, &count );
  22. while (inrec.EventType != KEY_EVENT);
  23.  
  24. // Restore the original console mode
  25. SetConsoleMode( hin, mode );
  26. }
  27. }

You can use it the usual way:
  1. int main() {
  2.  
  3. std::cout << "Hello world!\n" << std::endl;
  4.  
  5. console::pause();
  6.  
  7. std::cout << "\n\nThank you!" << std::endl;
  8.  
  9. return EXIT_SUCCESS;
  10. }

Enjoy!
Reply With Quote