[c] Preventing console window from closing on Visual Studio C/C++ Console application

This is a probably an embarasing question as no doubt the answer is blindingly obvious.

I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.

When I run my application the console window pops up, the program output appears and then the window closes as the application exits.

Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?

This question is related to c visual-studio console

The answer is


Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).

If this doesn't work then add the following to the end of your code:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

This wait for you to press a key to close the terminal window once the code has reached the end.

If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.


You can also use this option

#include <conio.h> 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
   .
   .
   .
   getch(); 

   return 0;
}

Either use:

  1. cin.get();

or

  1. system("pause");

Make sure to make either of them at the end of main() function and before the return statement.


In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.

  1. Go to "View" then select "Property Manager"
  2. Right click on the project/solution and select "Property". This opens a Test property page
  3. Navigate to the linker then select "System"
  4. Click on "SubSystem" and a drop down appears
  5. Choose "Console (/SUBSYSTEM:CONSOLE)"
  6. Apply and save
  7. The next time you run your code with "CTRL +F5", you should see the output.

Here is a way for C/C++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.


You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.


If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.


Right click on your project

Properties > Configuration Properties > Linker > System

Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!

Now try it...it should work


Visual Studio 2015, with imports. Because I hate when code examples don't give the needed imports.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}

try to call getchar() right before main() returns.


Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:

  1. The debug window retains the contents of the WSL shell window that closed.

  2. The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.


Go to Setting>Debug>Un-check close on end.

enter image description here


Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://docs.microsoft.com/en-us/dotnet/api/system.console.readline for details.


(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).

"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.


If you're using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.


add “| pause” in command arguments box under debugging section at project properties.


A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won't pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

just put as your last line of code:

system("pause");

Goto Debug Menu->Press StartWithoutDebugging


Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.

  1. Create a batch file. I called mine runthenpause.bat, with the following contents:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    The first line will run whatever command you provide and up to eight arguments. The second line will... pause.

  2. Open the project properties | Configuration properties | Debugging.

  3. Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
  4. Change "Command" to the full path to runthenpause.bat.
  5. Hit OK.

Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.

I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to console

Error in MySQL when setting default value for DATE or DATETIME Where can I read the Console output in Visual Studio 2015 Chrome - ERR_CACHE_MISS Swift: print() vs println() vs NSLog() Datatables: Cannot read property 'mData' of undefined How do I write to the console from a Laravel Controller? Cannot read property 'push' of undefined when combining arrays Very simple log4j2 XML configuration file using Console and File appender Console.log not working at all Chrome: console.log, console.debug are not working