Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 755
Confident.Nerd Avatar asked Mar 23 '20 10:03

Confident.Nerd


People also ask

How do I stop my console from closing?

You can simply press Ctrl + F5 instead of F5 to run the built code. Then it will prompt you to press any key to continue. Or you can use this line -> system("pause"); at the end of the code to make it wait until you press any key.

How do I keep the console open?

Keep Console Open With the Ctrl + F5 Shortcut in C# The best approach for keeping our console window open after the execution of code is to run it with the Ctrl + F5 shortcut of the Microsoft Visual Studio IDE.

How do I stop C++ console application from exiting immediately?

Before the end of your code, insert this line: system("pause"); This will keep the console until you hit a key.

How do I keep the console open in C++?

Start the project with Ctrl + F5 instead of just F5 . The console window will now stay open with the Press any key to continue . . . message after the program exits.


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

like image 84
Adrian Mole Avatar answered Oct 22 '22 10:10

Adrian Mole