Imaginary
Imaginary

Reputation: 773

Using code from standard library to stop output from exiting in Turbo C++

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
        }

Upvotes: 0

Views: 270

Answers (2)

phoxis
phoxis

Reputation: 61940

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.

Upvotes: 2

Adriano Repetti
Adriano Repetti

Reputation: 67118

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');
}

Upvotes: 1

Related Questions