Monday, April 12, 2021

-- How to create an exit loop in C++ --

 This is another typical question from my students.

#include <iostream>
using namespace std;

int main()
{
    bool exit = false;  // Variable to be used to signal the exit.
    char question; // Variable holding the value to be entered from the keyboard
    int x = 1;
    while (exit == false)  // If the user indicated they want to exit skip the loop
       {
         cout<<"Hello World:" << x << endl ;
         cout << "Do you want to exit (Y/N): "; // Ask the question
         cin >> question;  // Collect the answer from the keyboard
         if (toupper(question) == 'Y') // Evaluate the answer and change the value of exit.
         exit = true;
         
       }
    return 0;

-- How to introduce a pause in your C++ program --

 I often get asked by my students how to introduce a pause on their C++ program, the problem is that depending of the IDE you are using, after your program executes is closes the command line window automatically, so here are my 2 favorite approaches.

 Windows Operating System


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

int main()
{
    cout << "Please press any key to continue";
    system("pause");
    return 0;
}

If you are using either Linux / Unix unfortunately the pause command does not work, but you can use something like this


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

int main()
{
    cout << "Please press any key to continue";
    cin.ignore();
    return 0;
}