Search code examples
c++cvisual-studio-codeconsole

How to make sure console doesn't close immediately when running code?


I'm trying to learn C programming, but when I run my code the cmd, window closes immediately, without giving me the change to see if the program printed the result I was aiming for.

I'm coding C on VS-Code, using several extensions. Is there a setting/extension/code snippet, or anything I can do so it won't close immediately?

Thanks!


Solution

  • The easiest (and most common) way to do this is to add the line system("pause"); immediately before the return 0; statement in your main function:

    #include <stdio.h>
    #include <stdlib.h> // This header defines the "system()" function
                        // For C++ builds, #include <iostream> will suffice
    
    int main()
    {
        printf("Hello, World!\n");
        system("pause");
        return 0;
    }
    

    This call will produce a prompt and await a key-press from the user. The exact message displayed may vary between compilers and/or platforms but, with Visual Studio and MSVC, the message is:

    Press any key to continue . . .