Bits & Bytes

Keeping the C++ Console Window Open

One of the first problems that new C++ programmers have is keeping the console window open when writing C++ programs. The easiest solution to this problem is to use the Start Without Debugging option under the Debug the when executing programs. Unfortunately, Microsoft took this option and many others out of the default menus in Visual C++ 2010. To get this option back, select Tools->Settings->Expert Settings. Otherwise, you can use press (Ctrl + F5) to select Start Without Debugging without the menu.

That’s the simplest option for keeping the console window open. However, if you want to keep the window open when running an executable that you create, you will need to add some code to suspend execution and keep the window open. Below, we show one example of how to keep the window open by adding this line of code before the return statement:

system("pause");

The one objection I have to this method is that the system() function is not part of the C++ standard and may not be valid with some C++ compilers.

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    system("pause");
    return 0;
}

Alternatively, we could use cin.get(); to keep the window open like this:

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    cin.get();
    return 0;
}

However, using cin.get() can have problems if input is taken directly before it. The problem is that the input in the stream carries over to the cin.get() and causes the program to exit. To prevent this, we can add a call to clear() and ignore(), as we do below.

#include <iostream>

int main()
{
    using namespace std;

    int iInt;
    cin >> iInt;
    cout << "Input = " << iInt << endl;

    cin.clear();
    cin.ignore(0xFFFFFFFF, '\n');
    cin.get();
    return 0;
}

Tags: , , , , , , , ,

Michael Hall

By: Michael Hall

One Response to “Keeping the C++ Console Window Open”

  1. Devlin says:

    Yo I just wanted to thank you for all the C++ videos, they have been incredibly helpful, and you do a very good job at explaining the code snippets you use. Your explanation of pointers and references was significantly better than most people, they are really easy topics to understand, but somewhat difficult for most people to explain.

    Leaning C++ from the web can be difficult because no matter how many tutorials someone makes they always miss something, so the learner has to watch multiple videos/read multiple articles to fully understand a particular topic, and this website has been a main source of information for me.

    Your time invested in your video tutorials is very much appreciated.

    Thanks a lot,

    Devlin

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.