Confident.Nerd
Confident.Nerd

Reputation: 77

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!

Upvotes: 5

Views: 6117

Answers (4)

Jasper Kent
Jasper Kent

Reputation: 3676

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.

Upvotes: 1

Zach Hammond
Zach Hammond

Reputation: 26

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");.

Upvotes: 0

Landstalker
Landstalker

Reputation: 1368

You can use getchar ():

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

Upvotes: 3

Adrian Mole
Adrian Mole

Reputation: 51815

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

Upvotes: 4

Related Questions