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

Viewed 4088

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!

5 Answers

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 . . .

You can use getchar ():

#include <stdio.h>
int main()
{
    printf("Hello, World! (presse enter to leave)\n");
    getchar (); //<-- presse enter to leave
    return 0;   
}

This is an odd feature of Visual Studio.

If you run a console application without debugging (ctrl-F5) then Visual Studio automatically holds the console open for you when the program terminates.

It does not do this when you run in the debugger (F5) - the expectation being that you can hold the process open for yourself with a breakpoint somewhere.

In C++ it can be as simple as this:

#include <iostream>

int main()
{
    std::cout << "Press any key to exit.\n";
    std::cin.ignore();
    return 0;
}

In C, I would go with Landstalker's answer.

Or set a breakpoint (F9 on default) at the last statement (return 0;), then continue (F5 on default) when you want to exit your program.

I can't comment, so I'm making a quick answer. VS didn't use to stay open when a program was finished. You had to use system.("PAUSE"); to keep it open. But, VS changed that so once the main function returns, it halts the command prompt for you. Most IDEs don't work this way, and running outside of an IDE will not work this way, without some added intervention in your code, like system.("PAUSE");.

Related