Search code examples
c++cstandard-libraryturbo-c++

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
        }

Solution

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