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

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?

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

Starting from Visual Studio 2017 (15.9.4) there is an option:
Tools->Options->Debugging->Automatically close the console
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.

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.

Goto Debug Menu->Press StartWithoutDebugging

If you're using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER>.

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

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

just put as your last line of code:
system("pause");

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.
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.
Open the project properties | Configuration properties | Debugging.
Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
Change "Command" to the full path to runthenpause.bat.
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.

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

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.

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.

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

Either use:
cin.get();
or
system("pause");
Make sure to make either of them at the end of main() function and before the return statement.

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;
}

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

Sometimes a simple hack that doesnt alter your setup or code can be:
Set a breakpoint with F9, then execute Debug with F5.

Since running it from VS attaches the VS debugger, you can check for an attached debugger:
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached. Press any key to exit.");
Console.ReadKey();
}
I guess the only caveat is that it'll still pause if you attach any other debugger, but that may even be a wanted behavior.

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

Visual Studio 2015, with imports. Because I hate
when code examples don't give the needed imports.
#include <iostream>;
int main()
{
getchar();
return 0;
}

Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.

It should be added that things have changed since then. On Windows 11 (probably 10, I can't check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.
If it's set to close when a program exits with zero, then it will close, even if VS is told otherwise.

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

Related

My C code is not running in Microsoft VS CODE

#include <stdio.h>
int main()
{
int a,b;
printf("Enter the value of a\n");
scanf("%d",&a);
printf("Enter the value of b\n");
scanf("%d",&b);
printf("The sum of a and b is %d", a + b);
return 0;
}
When i run this code in Microsoft Visual Code the code doesn't stop executing nor do i get the output. It starts running but it does not stop. I am also not getting any output. Other type of code is working perfectly fine.
Anyone can help me with this?
click here for image from vscode showing the running window
The code you have written is 100% correct.
Take care of the following things, check it out, if you have done them:
Install gcc in your system. gcc helps u compile c or c++ codes.
Install a C/C++ extension from the extensions section in the visual studio code.
At last, if the situation is still the same, try to re-install the visual studio code.
I hope, this might helps you. If you liked my suggestion, please press the upvoke button to motivate me to write such answers for you.
Thanks!
if this thing happens again first again try to execute the same code with some other IDE or run your code separately with CMD or PowerShell.
Code runner extension runs code in the output file which can not be interacted with. You have to change it so it runs in the terminal.
Go to the menu Code > Preferences > Settings.
In the User tab on the left panel, expand the Extensions section.
Find and select Run Code Configuration.
Find and check the box Run in Terminal.
I had exact same problem and it turns out I forgot to save the code:)
The main reason why code is not running is because it is running in "Output" Window, which I had shown in the linked Image.
If you want to run code properly then you have to run it in "Terminal" Window.
For running your code in "Terminal" window you have to follow these steps:
Step 1: Open Settings.
Step 2: Then type "Run in Terminal" in search box of the setting. Scroll below and find that setting.Install code runner if you haven't.
Step 3: Tick the box which is in 2nd line.
After that your code will run properly.

Where should I be looking for the output in visual studio?

So I am not a programmer but I've decide to learn C and have found a website with great material (https://www.learn-c.org/). As a student I was able to get Visual Studio Enterprise 2017 for free. So as you may understand I'm not well versed in either C, programming, or VS2017. For lesson 1 on this site I must create my own Hello_World program. In VS2017 I opened an empty project and then opened a new file (Test.c). I believe my code is correct, however when I try to run it (Shift + F5) I do not see the "Hello World". A command prompt flickers on my screen for a bit. In a panel labeled "Output" on the bottom of VS 2017 I get this:
1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>Test.c
1>Project1.vcxproj -> C:\Users\Fabien\source\repos\Project1\Debug\Project1.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
So my question is where should I be seeing "Hello, World!" ?
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
}
You program is working correctly but it is executed in a separate window and it is closed immediately after it finishes so you don't get a chance to see the output. You can use a function that halts the program and waits for input, for example getchar like so:
#include <stdio.h>
int main() {
printf("Hello World");
getchar();
return 0;
}
this way the program will wait for input and then close.
Shift-F5, unless you've reconfigured the default keys, is to stop debugging, so I'm not sure why you think that would help :-)
Pressing F5 on it's own will run your code, but in a mode that means it will simply exit once done, and the output window will disappear. If you need to do it that way, you can simply put a getchar() before exiting.
However, I'm not a big fan of having to change code just for debugging and, in any case, exiting may occur somewhere other than the end of main().
So I find it preferable to simply use Ctrl-F5 to run it in such a way that the IDE itself will leave the window open until you press a key:
<Your program output goes here>
Press any key to continue . . .

How to remove execution related text from output window of Code::Blocks

I am using Code::Blocks for programming in C. When I compile my program and execute it, the output window (i.e.. Windows Command prompt) displays some execution related text, these texts are not of use to me right now and dont want them to appear(see text below).
Hello, World!
Process returned 0 (0x0) execution time : 3.920 s
Press any key to continue.
I tried to change the settings in Code::Blocks but couldn't find any settings related to the output window and also I dont want the text "Press any key to continue" to appear. These texts appear only if I run the program through Code::Blocks and doesn't appear if I directly run the program.
Unfortunately, some things just cannot be changed, and that is one of them. There are some quirks used by some IDE's that just drive programmers crazy, but it can't be helped. There is a reason why it's there: the execution data can be used to find out whether the program worked properly (e.g. ended execution). You can use this data later when targeting execution time as one of the main focuses in coding the project. There may be other uses for it as you code more and more advanced projects.
It only appears when you execute your code from the compiler. It does not need getch() function to stop the screen.
But if you execute its .exe file directly, outside the compiler, you will notice that annoying message 'Process returned 0 (0x0) execution time : 3.920 s' doesn't show anymore. Moreover, you will need getch() function to stop the screen.
you may need to include stdio.h and then call getchar() before return 0
for example;
#include <iostream>
//add this library
#include <stdio.h>
using namespace std;
int main()
{
cout<<"I am a C++ programmer! "<<"Awesome!";
//add this line of code
getchar();
return 0;
}

start a program without a console window (in background)

I want to start a simple program when windows start but I don't want to show the console output window associated with that program. Just to test, the program can be as simple as:
int main (int argc, char** argv)
{
while (1)
{
printf ("hello world...\n");
Sleep (10000);
}
return 0;
}
compiling it as: cl foo.c
I know how to start the program when windows is starting (putting in startup folder, creating registry etc), but I don't know how to hide the console output window that comes when the program is started.
While searching for this, I found that I can use start /B foo.exe. Is there any other method for doing this? some thing like "&" we use on unix.
My actual program is big and is written in C, so I can not use some other alternatives i found for c# (like WinMain) and java (like explained here).
This should work.
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdParam, int iCmdShow)
{
for (;;) {
//action here
}
return 0;
}
WinMain is not a C# entry point. C# uses a method of a static class; it is called Main by default, but can be configured to any static-class method.
In Windows, non-console C programs should define a WinMain. You can then link them using the linker's /subsystem:windows command-line option, invokable either directly or from CL.
One method is calling FreeConsole() as first thing in main. It will hide the console window, if any.
Unfortunately simply setting FreeConsole() as the first function in main allows the window to appear momentarily anyway. And FreeConsole removes the window so that if you wish to use it later( as in killing the process ) you have to make it appear on screen in a mode out of your control.
Windows allows Win32 programs to have only one of four contexts under Visual Studio: Window program with initial GUI window, Console program with initial Console window, DLL or Lib. Changing the subsystem to a non-Console choice from the project->Properties->System view only results in linking issues that block the build.
Here is what worked for me with only a little effort. Use Mike's approach above and choose Win32 Project with Window Application. Then delete everything in WinMain after the "Place code here" direction and delete all the called functions. Return true or 1, as you wish from WinMain. No window of any type will appear on launch.
And when you are ready to deal with a Console Window call AllocConsole() in your code and deal with its positioning and size as you see fit. The Console can be positioned off screen and slid into view if you wish; it only takes a few minutes to get the handle on the configuring functions. Start with Microsoft's 'Console Functions' in MSDN documents. Unfortunately, there is no book on how to use all the functions properly as there is for NCurses in Linux.
When you're creating your project create one with WinMain instead ( Win32 Project ). If you still want the console later use AllocConsole() and FreeConsole().
If the program would be eg procexp.exe you can do this out of the box :
cmd /c "start C:\Users\denni\OneDrive\_bin\_tools\ProcessExplorer\procexp.exe"
WinMain isn't unique to C#. It's possible to write GUI applications in C too. The WinMain function is the entry point, but nothing says you have to actually create a window. You could have WinMain do nothing more than call the first function of your program to get it started. Then you'd have your program running with no GUI window and no console window.
Of course, this also means no easy way to stop it, short of killing it from Task Manager.

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista.
So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a simple hello world program, it runs, but the console window just flickers on the screen, and I can't see the output.
How can I see an the output of my C programs using Dev-C++? I found a C++ specific solution, System("pause"), and a really ugly C solution, while looping fflush(stdout), but nothing nice and pretty.
I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc
In Windows when a process terminates, the OS closes the associated window. This happens with all programs (and is generally desirable behaviour), but people never cease to be surprised when it happens to the ones they write themselves.
I am being slightly harsh perhaps; many IDE's execute the user's process in a shell as a child process, so that it does not own the window so it won't close when the process terminates. Although this would be trivial, Dev-C++ does not do that.
Be aware that when Dev-C++ was popular, this question appeard at least twice a day on Dev-C++'s own forum on Sourceforge. For that reason the forum has a "Read First" thread that provides a suggested solution amongst solutions to many other common problems. You should read it here.
Note that Dev-C++ is somewhat old and no longer actively maintained. It suffers most significantly from an almost unusable and very limited debugger integration. Traffic on the Dev-C++ forum has been dropping off since the release of VC++ 2005 Express, and is now down to a two or three posts a week rather than the 10 or so a day it had in 2005. All this suggest that you should consider an alternative tool IMO.
Use #include conio.h
Then add getch(); before return 0;
The easiest thing to do is to run your program directly instead of through the IDE. Open a command prompt (Start->Run->Cmd.exe->Enter), cd to the folder where your project is, and run the program from there. That way, when the program exits, the prompt window sticks around and you can read all of the output.
Alternatively, you can also re-direct standard output to a file, but that's probably not what you are going for here.
For Dev-C++, the bits you need to add are:-
At the Beginning
#include <stdlib.h>
And at the point you want it to stop - i.e. before at the end of the program, but before the final }
system("PAUSE");
It will then ask you to "Press any key to continue..."
Add this to your header file #include
and then in the end add this line : getch();
You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.
Add a line getchar(); or system("pause"); before your return 0; in main function.
It will work for you.
;
It works...
#include <iostream>
using namespace std;
int main ()
{
int x,y; // (Or whatever variable you want you can)
your required process syntax type here then;
cout << result
(or your required output result statement); use without space in getchar and other syntax.
getchar();
}
Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program.
It will show you the output window and it will not vanish with a second Until you click enter to close the output window.
i think you should link your project in console mode
just press Ctrl+h and in General tab select console.
When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.
The use of line system("PAUSE") will fix that problem and also include the pre processor directory #include<stdlib.h>.
Well when you are writing a c program and want the output log to stay instead of flickering away you only need to import the stdlib.h header file and type "system("PAUSE");" at the place you want the output screen to halt.Look at the example here.The following simple c program prints the product of 5 and 6 i.e 30 to the output window and halts the output window.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
a=5;b=6;
c=a*b;
printf("%d",c);
system("PAUSE");
return 0;
}
Hope this helped.

Resources