After compiling console programs the console window closes immediately after running. What is the best practice for keeping it open? I've searched google loads, I'm used to codeblocks where you don't have to worry about it, but, I want to mess around with Visual Studio a bit and with VS, my console closes. All over the interwebz there are several different ways to keep it open, however, I've read that most of them are bad coding techniques. What is everyones preferred method?
When I'm using Visual Studio and I don't need debugging I just run it using Ctrl+F5 keystroke – and it prevents console from closing.
Since you always run in the debugger, set a breakpoint on the return statement from main().
The debugger is your best friend, learn (and learn early) to use it to your advantage at every opportunity.
Run your program in a console, which would be the expected way of running a console program ...
Alternatively, you can make a little batch file to execute your program that would have:
REM batch file to launch program
yourprogram.exe
PAUSE
and the PAUSE cmd.exe command will ask to user to press any key.
I tend to use system("PAUSE"); which gives you a
Press any key to continue . . .
message.
cin is grossly inelegant but easy for the forgetful to derive:
{
char c;
std::cin >> c;
}
That holds the window open until you type a character /* edit */ and hit enter.
std::cin.get() will close the window the moment you type a character, which, depending on how easily you become habituated, runs a marginally greater risk of "whoops, I wish I hadn't closed that!" than the two-keystroke operator>>(istream &).
Both differ from a system("pause") in that they return in a program-accessible way the value of the character you typed, so, if as not infrequently happens, one kludge leads to another, you can write a switch statement based on what you typed to (for example) exit immediately, write some values to a log, run it again, etc.
I use:
cin.get()
I heard it was less costly than system("PAUSE") and it works on POSIX systems too.
There's a great link that goes into detail about this.
Resist the temptation to do anything. Well behaved command line programs exit when they've finished running reporting a status via their exit code. This enables them to be scriptable and 'good citizens' in automated environments. Even in an interactive environment, why force the user to make an extra key press just because of your debugging environment?
If you run, rather than debug then Visual Studio will open a console windows that pauses after your application exits so that you can still view the output. I don't know why the behaviour is different when you debug, perhaps because you have breakpoints available so if you want to see the output at various stages you can place breakpoints after the relevant output statements, or at the end of main or enable various 'stop on exception throw' options.
Whatever the reason, I've never felt compelled to compromise the behaviour of my application just to enhance my debugging experience.
A very common one is to just put in code to read a key from the console after your main application code closes. The keystroke read in just gets thrown away, but it holds the console open.
It's not pretty, necessarily - but I often do this wrapped in a debug define, so during debugging, the console is held open. During release, I'm usually not running inside VS, and when run from a command line, this is no longer an issue.
The "don't do that" responses in this thread may seem curt, but they're fairly sensible. I happened across this question because I'm debugging a gtest suite that used to run fine, but now crashes mysteriously when launched. When run from the console, it pops up a dialog saying "blah.exe has stopped working"; but, when run from the debugger, the console pops up momentarily, vanishes, and the program exits with 0 status.
I should have been thinking about how odd this difference in behavior was, but instead I was like: "Aw, man---I gotta make that console window stay up so I can see what it says." Right?
It turns out that the machine I'm working on (a colleague of mine's) had the 'Command Arguments' for the debugger set to '--gtest_filter=*testMsg*'. I noticed this right away, too, but it never occurred to me that all the tests matching the filter had been renamed in a recent commit. So, when launched from the debugger, gtest wasn't finding any tests to run and was simply exiting. Another 90 minutes of my life I'll never get back. (-_-) I could have ditched this tar baby a lot sooner if my knee-jerk reaction hadn't been to think I needed that console window to stay open in order to solve the problem...
Call this function before you return at the end of main:
void onEnd()
{
printf("Press any key to exit...");
_getch();
}
You can specify that the executable is a Console app, not a Windows app, at least in VS2017. This makes your application run in a "Microsoft Visual Studio Debug Console", with "Press Any Key To Close This Window" appearing at the end of the console output:
Right click the project to bring up Properties.
Linker > System > Subsystem > Select "Console".
Press Apply before closing.
Related
I just started learning c++ and while reading the c++ tutorial in http://www.dev-hq.net/c++/1--the-basics i saw that writing a c++ program in some text editor is different from writing one in visual c++. It said something like "Visual C++ will require some sort of application pausing before the end of the 'main' function in most cases as it generates a window which will disappear after execution".
what does this mean?
Short Answer: It isn't mandatory. The site suggests so that the output in the console window can be seen before the program exits (thereby closing the window).
Long Answer: If you're using an IDE to develop a C++ or C program with no GUI, the output is shown by the IDE by launching the console/terminal window (also called the command prompt). This window is shown as your program is started and closed immediately when your program ends. Say if you just print "Hello, world!" and don't give any pause, the terminal window would open, show Hello, world! and immediately close, all in a blink of an eye. So it's customary that a pause is inserted in the end. This problem isn't seen on all IDEs; some show the output in its own integral window, some insert the pause behaviour through script, etc.
It is to be understood that this is just a hack to make the window stay and making a blocking call to do so is useless from the program's viewpoint. Also don't use system("pause"); as it has issues, apart from the fact that it's not portable and works only on Windows platforms.
#include <iostream>
#include <limits>
int main()
{
std::cout << "Press ENTER(s) to exit...";
// flush data in cin's buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// blocking call to fresh input from user
std::cin.get();
}
This would be a portable way i.e. irrespective of the platform you're using it will work.
An alternative is to use getchar (not the similarly named getch) which is portable as mandated by ISO C Standard but it has its quirks.
Another way would be to put a breakpoint as suggested by Raja. It'll also get your feet wet in learning the debugger, an essential tool in programming.
To avoid the issue altogether run the program yourself from the console window. Although sometimes it may get a bit tedious for a beginner, hand compiling code and running it yourself without an IDE gives you more insight and is a good learning experience.
I'd still recommend hand compiling or the debug breakpoint methods instead of injecting a fake pause/blocking call in the program; notice that the input received from the user is just ignored and never used in the program further down the line and thus is redundant from the program's standpoint, hence the recommendation to not use it.
When you use "Run Project" (Ctrl+F5 in the classic Visual-C++ key binding, not just F5, which is "Debug Project"), Visual Studio will keep your console window open until you press a button.
It's only when you use "Debug Project" that it doesn't. This makes sense, because you generally only want to use that option (which has a much longer startup and shutdown time and runs slower) when you're actually hunting a problem, in which case you probably have breakpoints set in your program and can simply set one on the last line of main().
So all the proposed workarounds, and the flames about Visual Studio, are simply unnecessary and wrong.
It just means that the executable window will close as soon as it's done executing.
I would recommend using a simple getchar(); statement from the standard library (<iostream> or <stdio.h> header) before you return 0;. This means you will have to press a key for the window to close. As you mention Visual C++, system("pause"); will work as well before the return on Windows systems.
Of course, if you return from main earlier (common with error codes, unhandled exception, or an exit call somewhere), you likely won't get to that pausing mechanism. As you are just starting out, it is unlikely you will run into that stuff for now though.
Running your program from the command line will work as well to see the output.
Here is something I use to pause my console applications and let me see the results:
void waitForUser()
{
// if for some reason cin is in invalid state
// we need to clear it
std::cin.clear();
// if we used cin to input something it is likely to
// contain trailing \n symbols , we need to get rid of them
std::cin.ignore( std::cin.rdbuf()->in_avail() );
// we wait for a user to hit Enter here
std::cin.get();
}
Just put a call to this function at the end of main
I installed Codeblock a week ago and have not changed any setting. I created a simple console application and when I clicked build and run it display my output for like milisecond and disappear... It used to stay forever until I exit it. Anyone know why is this happening? In the Build log tab it says "Process terminated with status 0 (0minnutes, 0 seconds)
You don't have any problem actually, neither in your Codeblocks Application nor in your code, But codeblocks doesn't wait for you to close its console window manually, It automatically does it.
You've 3 ways, choose that suits you better
Go to Menu Bar and toggle 'show output window'
Alternatively you can append a C++ code that waits for an event to happen, so that you may get enough time to watch your Output.
You can use the code which I've given below
It will be definitely good if you choose to see your output message through debugging(Step Over). It will also improve your debugging skills.
If you want to choose second approach then append following code in your application
#include<conio.h>
int main()
{
// After your code - write
getch();
return 0;
}
Note:- I believe you're using codeblocks on Windows Platform, this code will work fine on windows, but <conio.h>
won't be available to you if you want to port your program from Windows to Linux
I'll recommend you to give them preference in this order [3 > 1 > 2]
for those who may encounter this error:
all you need to do to make the console not dissapear is this:
go to project properties.
click on build targets
there is an option below console application "pause when execution ends"
check it and you are good to go!
Hope this helps
Use :
#include <iostream>
//...other includes....
int main()
{
/*Your Code */
//...
std::cin.ignore(); //wait for Enter, will makes the console to stay.
}
You may be clicking on the red arrow, however click on the "build an run" arrow instead, which has a little cog and a green arrow.
Solution if you are copying and pasting input: For me, the issue was that I was copying and pasting my input file from the web. Presumably, this copied some invisible characters, such as a return, which my program registered as the user having pressed any key to continue. The solution I used was to download the file to my computer, then run my program in command prompt, piping the input into the .exe file in the following manner:
C:\Project Directory> myProgram.exe < myInputFile.txt
Many of my professors recommend running programs from the command line, and I advise using this tactic as it is quick and lets you skip manual typing. Also, you can save the output of your program to a desired file, rather than having it print on the command line, by doing the following:
C:\Project Directory> myProgram.exe < myInputFile.txt > programOutput.txt
Hope this helps.
When I compile a program and run the exe file it automatically closes. Is there any way to avoid it? I know you can put system("pause") but I heard that it is recommended not to use it, or you can put in a cin at the end and wait for the user press something before closing. But is there any "real" official way to make the program stop?
Are you using Visual Studio? if yes and its a version before 2010 then CTRL+F5 will do the trick
if its a version after....
this might help
http://connect.microsoft.com/VisualStudio/feedback/details/540969/missing-press-any-key-to-continue-when-lauching-with-ctrl-f5
Your program does, what you want it to do.
It means, for 'C++', terminating, when there is no more instructions to run.
You have plenty of methods to stop your program (waiting for some signal, receiving data from socket, ...). Reading from stdin is probably the easiest way.
system("pause") is not recommended because it just calls system function Pause and in some environments there could be no such function.
If you "Start Without Debugging" Ctrl + F5, then the after the program exits the console window remains open and a Press any key to continue . . . message is displayed until you press any button. That's the best solution, since it doesn't require any code modification, while if you debug, you can set a breakpoint anywhere you want.
Works with all version of Visual Studio, pretty standard thing.
Windows solution for visual studio compiler only:
fflush(stdin);
getchar()
So I keep getting this error when trying to compile C++ code using CodeBlocks.
cannot open output file [filename.exe] permission denied
It only started today, and it's sporadic and inconsistent. It usually goes away if I shut CodeBlocks down and restart the project, but not always. Sometimes it even goes away when I just press F9 (build & run) several times. I always check Task Manager, but there are never any .EXEs running with my file's name, or anything related to it.
I've also noticed that if this problem occurs and I then try to delete the .EXE manually or otherwise interact with it, Windows tells me I need administrator permission to do so (this is a private PC, and as far as I know I am an administrator on it).
The first time it occurred, the only thing I had added to the code beyond what was in the previous version was a debugging report sent to cout - hardly anything arcane. It sometimes occurs even when no code was changed from a previous version.
What could this be? It's not game-breaking, yet, but it's irritating and I'd rather it didn't get worse.
EDIT: This is old by now, but just in case anyone else is having similar problems, the workaround I currently use is just to consistently delete [filename.exe] before trying to run the code again. This avoids the problem, though it is annoying.
check that "filename.exe" is not running, I guess you are using Microsoft Windows, in that case you can use either Task Manager or Process Explorer : http://technet.microsoft.com/en-us/sysinternals/bb896653 to kill "filename.exe" before trying to generate it.
I have encountered the same problem you have. I found that it may have some relationship with the way you terminate your run result. When you run your code, whether it has a printout, the debugger will call the console which print a "Press any key to continue...". If you terminate the console by pressing key, it's ok; if you do it by click the close button, the problem comes as you described. When you terminate it in the latter way, you have to wait several minutes before you can rebuild your code.
I just had the same issue. And i experienced that it always happens when i run the programm and change some code without finishing the programm still running. After that the "cannot open ..." message appears.
However i got rid of it by clicking the "Terminate" button at the very top-right side of the console window (red button) and after that "remove all terminated launches" (two x'es right next to the terminate button).
This seems to close the running programm and everything works fine after :) hope this may help anyone
I was having the same problem too and it was driving me crazy:
Windows7 64 bit, MinGW, Eclipse, CDT
Permission denied errors, executable disappearing, ld.exe errors. It would work once, but never again.
Statements like: "cannot open output file ***.exe: Permission denied"
Check your ANTIVIRUS Software. Once I turned off my Antivirus software in workspace then cleaned the workspace and started the project over again I never had the problem again.
This error usually occurs when the IDE has a problem due to a crash or other failure and it still has a hold on the EXE, preventing the user (yourself) from overwriting / deleting the EXE during a rebuild.
Hello I realize this post is old, but here is my opinion anyway.
This error arises when you close the console output window using the close icon instead of pressing "any key to continue"
The problem is related to Sam´s response:
"have encountered the same problem you have. I found that it may have
some relationship with the way you terminate your run result. When you
run your code, whether it has a printout, the debugger will call the
console which print a "Press any key to continue...". If you terminate
the console by pressing key, it's ok; if you do it by click the close
button, the problem comes as you described. When you terminate it in
the latter way, you have to wait several minutes before you can
rebuild your code."
Avoid kill processes, and we have two choices, wait until the process release the .EXE file or this problem will be solved faster restarting the IDE.
You can use process explorer from sysinternals to find which process has a file open.
Try restarting your IDE. It worked for me.
Although I tried to end the process in the task manager, the process never got killed.
I re-installed C::B in drive D, whereas my program files folder is in drive C
I don't know the reason , but it works :)
well,once i had the same problem and after tracking down the process that was getting the file in use i discovered that it was the anti-virus (PANDA) ...i just unlocked the file and simply worked out ....well for my experience i used Unlock 1.9.2 ...try iy out ..
A major cause of this (which I had recently), is if you have this on for example a flash drive.
You can develop and do everything, but on most systems it stops you from running the .exe file from there, whether it be the debug or release version.
In my case - I found a process called
cb_console_runner
I stopped this process and things were ok again.
I had the same Problem. Just rename your .CPP file to other name and try it again.
It worked for me.
FOR LINUX OS...
go to file where u r created file.then usually
......project_name/bin/Debug/project_name.executable here for this executable file you wont be having execute permission then the execute permission.Either by right click if you are unable to change permission then use use open terminal(command promt) to change permission.
first go to that executable file using 'cd' command then use "chmod u+x" then permission is going to change.then go to c::b open and execute you will get output.
only thing for all file u need to do it.
The problem is that you don't have the administrator rights to access it as running or compilation of something is being done in the basic C drive. To eliminate this problem, run the devcpp.exe as an administrator. You could also change the permission from properties and allowing access read write modify etc for the system and by the system.
Make sure to run 7zip in 'Administrator mode' for extracting to Program Files.
Also, temporarily turning off virus protection worked for some people in the past.
I tried what #willll said, and it worked. I didint find exactly the .exe named after my project, but I did kill some weird looking tasks (after checking on the internet they were not critical), and it worked.
I have tried and get output after end task IDE from task manager. Later clean all temporary files from your drive. Start your IDE. Now your .exe working good.
I have a console application that runs some temperamental hardware. If I don't detach from it nicely, windows tends to bluescreen five minutes later. I can catch when the application is closed by using SetConsoleCtrlHandler. But when I hit 'stop debugging' in visual studio, it skips this process and just kills the program brutally. As of 2009 it appears nobody has a solution for this problem.
Is this still the case? Do I really have to live with a bluescreen if I accidentally hit the wrong button?
Killing the process is what that button is for. If you want the program to terminate gracefully, you need to let it run to completion. You can use the debugger's "continue" button, or just detach from the process, and then quit the program in the normal way. Or you can use the debugger to do something that makes the program quit itself, such as setting a "done" flag that controls a main loop.
You might consider splitting your program into two parts: a service that deals with the hardware's peculiarities and presents a "clean" interface to the console application, and the console application which talks to the service instead of directly to the hardware.
You immediate problem is the TerminateProcess function that even Task Manager can execute which gives you no recourse to shutdown cleanly. Even if you could solve the Visual Studio problem, someone could right click and "End Process" and you be in the same boat.
Your root problem is poorly-written device drivers. These driver should not blue-screen even if you are abruptly terminated. If you have choice but to use them then you can try to bulletproof your process by running with administrative privileges, running as a service, or confining operations to short windows of time. Or you can simply train your operators not to do the things that will cause your delicate system to blow up. And hope.