Search code examples
c++pausing-execution

A valid loop for pausing a program after it ends


I'm a novice programmer and have been learning C++ recently, after some research in how to pause my program at the end I upgraded from

system.get(); 

to a

cin.ignore();   
cin.get();  

combo. Would I be better suited to writing an if loop to wait for input at the end to close out the program, I understand that later in my experiences pausing the program at the end will cause user errors at the end.

I'm looking for the better way to do this.


Solution

  • In general, you don't need a loop to wait for the User to press a key.

    Try:

    std::cout << "Paused.  Press ENTER to continue.\n";
    std::cin.ignore(10000, '\n');
    

    This does not rely on the OS having a "pause" command.

    Note: you may need a loop if you are polling for a keypress. Detecting a keypress is an operating system function, and you need to use specific OS API.