How To: Pause A C++ Program

Windows example:

#include <iostream>
using namespace std;

#include <cstdlib>

int main()
{
  cout << "Hello..." << endl;

  _sleep(5000); // wait 5 seconds
  cout << "Goodbye!" << endl;
  return 0;
}

GNU example:

#include <iostream>
using namespace std;

#include <unistd.h>

int main()
{
  cout << "Hello..." << endl;

  sleep(5); // wait 5 seconds
  cout << "Goodbye!" << endl;
  return 0;
}

Windows example: a digital clock

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

#include <cstdlib>

int main()
{
  cout.fill('0');
  for (int hr = 0; hr < 24; hr++)
  {
    for (int min = 0; min < 60; min++)
    {
      for (int sec = 0; sec < 60; sec++)
      {
        cout << setw(2) << hr << ':';
        cout << setw(2) << min << ':';
        cout << setw(2) << sec << ' ';
        cout.flush();
        _sleep(1000); // one second
        cout << '\r'; // CR
      }
    }
  }
  return 0;
}

GNU example: a digital clock

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

#include <unistd.h>

int main()
{
  cout.fill('0');
  for (int hr = 0; hr < 24; hr++)
  {
    for (int min = 0; min < 60; min++)
    {
      for (int sec = 0; sec < 60; sec++)
      {
        cout << setw(2) << hr << ':';
        cout << setw(2) << min << ':';
        cout << setw(2) << sec << ' ';
        cout.flush();
        sleep(1); // one second
        cout << '\r'; // CR
      }
    }
  }
  return 0;
}

Combined example of the digital clock:

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

#ifdef __GNUC__
#include <unistd.h>
#endif

#ifdef _WIN32
#include <cstdlib>
#endif

int main()
{
  cout.fill('0');
  for (int hr = 0; hr < 24; hr++)
  {
    for (int min = 0; min < 60; min++)
    {
      for (int sec = 0; sec < 60; sec++)
      {
        cout << setw(2) << hr << ':';
        cout << setw(2) << min << ':';
        cout << setw(2) << sec << ' ';
        cout.flush();

#ifdef __GNUC__
        sleep(1); // one second
#endif

#ifdef _WIN32
        _sleep(1000); // one second
#endif
        cout << '\r'; // CR
      }
    }
  }
  return 0;
}