Question

Many of folks here are telling me to stop using clrscr(), getch() etc. and I have started learning C++ with the standard library and now that I want to follow the standard library how would I stop the output from immediate exit after run?

include <iostream.h>
include <conio.h> // Instead of using this

    void main(){
        cout << "Hello World!" << endl;
        getch(); // Instead of using this
        }
Was it helpful?

Solution 2

Just replace getch() with cin.get() like this:

include <iostream>

using namespace std;

void main()
{
    cout << "Hello World!" << endl;
    cin.get();
}

For more details see get() function documentation. Just for reference you may do this, for example, to wait until user pressed a specific character:

void main()
{
    cout << "Hello World!" << endl;
    cout << "Press Q to quit." << endl;
    cin.ignore(numeric_limits<streamsize>::max(), 'Q');
}

OTHER TIPS

You can directly run the binary from command line. In that case after the program is finished executing the output will still be in the terminal and you can see it.

Else if you are using an IDE which closes the terminal as soon as the execution is complete, you can use any blocking operation. The simplest is scanf (" %c", &dummy); or cin >> dummy; or even getchar (); and what Adriano has suggested. Although you need to press Enter key, as these are buffered input operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top