C++ Run and closes when finish? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop C++ console application from exiting immediately?
I'm currently learning C++ and cant figure out how to stop the application from exiting when I want to show the user some data, and have time to read it. How may i do that?
Update: Somehow I pause the application and when the user click a button it exits.

I assume you're on Windows.
This can turn into a long debate, but generally there are two main ways people do it:
(recommended) Add cin.get(); to the end of your program. This will cause your program to stop until the user hits enter, then it will continue and quit.
This will work on Windows and Linux.
Add system("PAUSE"); at the end of your program. This will cause your program to print something like Press any key to continue. . . and when you hit a key, the program will continue and quit.
There is a chance that the PAUSE command doesn't do that and can order pizza, launch the missiles, or something else.
This only works for Windows but you won't need it when you go to linux anyway.

std::cout << "Press enter to exit" << std::endl;
cin.get();
exit(1);

If you want to pause your program until the user presses a key, you can use cin.get(). But really, the program should terminate when it's finished. Otherwise, it's useless in pipelines and the like.
If your program's window goes away when it's finished, then something is wrong with the way you launched it. Whether the window stays when the program is done is up to the thing that launches the program and sets up the window, not the program. This problem is usually caused by launching CLI programs from a GUI. If you want to launch from a GUI, write a GUI program. Otherwise, launch terminal programs from the terminal.
Do not use system("pause");. It makes your program unportable. And if you ever run it on a system whose pause command does something other than what you want, you may have a very angry user on your hands.
Do not use getch. That's a Windows console function and a Curses function. It's not part of C++. (Unless you are specifically developing for a platform that has this function and you are sure it does what you want. But this one function would be a really silly reason to make your program unportable.)

Related

how to prevent a program from totaly terminating when its console closes [duplicate]

This question already has answers here:
Graceful exit when closing console window
(2 answers)
Closed 20 days ago.
I am making a console app, and I want my program,to do some cleaning up, after you close its console
I researched a lot but I haven't found any good answer to this
There are many ways for a process to be terminated—closing the console window is just one. In general, you cannot depend on being able to clean up on close. Alternatives are to clean-as-you-go and/or clean-up leftovers on the next launch.
If you're worried only about the closing the console situation. Here are a couple options on Windows. Unfortunately, neither of them is trivial to implement.
Rather than creating a console app, create a "Windows" app that doesn't have a GUI and instead creates its own console. When the user closes that console, the process will still be running. I cannot remember if there's a way to attach your "Windows" program to the console it was started from. If there were, I think Visual Studio would have used that rather than the devenv.com and devenv.exe trick.
Create a console app that launches a second (non-console) program. The second process is your main program, but it to direct its output to the console app (e.g., using a named pipe). Likewise, the console app would have to direct user input to the second process. If the user closes the console (or the console app), the second process can continue to run.

Is there a way to have the console close automatically after a user inputs my restraints of an "Incorrect" answer in Visual Studio?

Im new to c++ and just started my first class last week. Im doing all my c++ programming in Visual Studio. My program states that a user type in an integer from 1 to 15. They have two attempts and if they fail to enter in an integer between these number the program exits. If they do type in an integer from 1 to 15, itll sum up all the integers from zero to that number and the program completes.
My question is, is it possible to have the console window completely exit after the failed attempt yet continue to stay open when the user gets it right even though the program is finished and you just have to press any key to exit? The console window stays open for both outcomes obviously the program will run its course and the console will debug and you have to press any key to exit which ever the outcome. Of course the right answer will give you additional information.
Im trying to emphasize the error/incorrect portion of the assignment by having the console window completely exit. Is this stupid? Possible? or is having the debugging prompt enough to show the program has exited?
Thanks again for anyone who can offer some feedback!

Does visual c++ require application pausing before the end of the 'main' function

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

Is there anyway to get the console window to stay open once program is done and close after 1 keystroke?

A command line program always closes the window after it has finished executing. I know you can use cin.get(); to wait for the user to enter input. Is there a way where the user could press any key (instead of entering something then pressing enter) to close the program? I don't want to use system("PAUSE") as it's Windows specific and slow.
I want it to pause so that the user can see it completed successfully and other details. It would probably not be run from an already open command line and the executable would be double clicked to run.
Yes. "system("PAUSE") is one way. A simple "getchar()" or "cin" should be absolutely equivalent :)
It's an option with the OS and not in C/C++. It needs to control how the Terminal open and close.
Just like if you called a batch or a command line app.
It's too platform dependent to post a code or config here (basically a Console GUI application with onClose statement in our IDE)

What is the Best Practice for Combating the Console Closing Issue?

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.