Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'.
In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method.
Is this a vagary of windows 7 and will it cause problems further down the line? It's no problem doing this at the moment but since this is not included in the book I was wondering if it might be something I've set up wrong.
Many Thanks :)
Use _getch() in place of getch()
getch() is not operating system specific, but it is not directly portable. The preferred method for doing this in C++ is to use std::cin.get();.
The main function can return 0 implicitly (you don't need to actually have that code, see below).
int main()
{
// valid, return 0 implied.
}
See this question for more details about the implicit return 0 from main.
When a program ends, any resources created by that program including the terminal window will be released. By using getch you prevent the program from ending. This is normal behavior and should continue to work that way until Windows is a distant memory.
If you start the program from within an already existing command window, the window will not close because it wasn't created by the program.
First, getch() isn't a standard C or C++ function. Even under
Windows, I think its use is deprecated; its semantics go back to CP/M
and early MS-DOS.
Secondly, it really isn't necessary, at least not for console apps (and
I don't think it's available for non-console apps). If you're running
the program from a console window, the window stays open. And if you're
running it from Visual Studios, it's trivial to set a breakpoint on the
return statement, which blocks the program, and keeps the window open
(although there's really no reason for the IDE to close it just because
your program has terminated).
Related
So, if you don't really know what do I mean, there's a small explanation. I'm also new in C++ so I need help with some things, so yeah. There's the explanation.
If you make a code, for example
cout << "Hello world!";```
-- I forgot how to make it fully good, but that's an example
Then it prints and closes extremelly fast. So, how can I make it so that it DOESN'T dissapear?
I am assuming you are talking about console window that closes fast.
In order to prevent that there are multiple ways of doing it. But i will write two simplest ways of doing so.
Add header at the top of your C++ program
#include <stdlib.h>
Then in the end of main function just before return 0 write this line of code
system("pause");
Another way of doing this is to get any character input before return 0. So write these lines of code
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
One of the simplest solutions is to use std::getchar() or
std::cin.get(). The program will wait for user input.
However, if there are already characters in the input buffer, then the program, roughly speaking, will ignore and will not wait for input from the user.
If the program is specific to Windows, then one of the most common solutions is to use std::system("pause").
For std::system(), you must also include the cstdlib header.
But it would still be better to set a breakpoint at the end of the program or, if your IDE allows (for example Visual Studio), then enable the option that leaves the console opened even after exiting. For example, VS allows you to run a program in non-debug mode, which does not close the console. To run the program in this mode, you can press the key combination Ctrl + F5.
However, in this case, in the project settings there should be Subsystem option in the System section in the Linker. And the value of Subsystem should be /SUBSYSTEM:CONSOLE.
I know there have been many work around proposed for immediate shutdown, but I was wondering if there is other way to do so for cross platform?
I think system("pause") is visual studio / windows specific and getchar() or other similar stuff that waits for users' input create unnecessary input for exiting the program running under say gcc.
Any idea?
-- Edit --
I also tried hitting Ctrl+F5, but it doesn't work sometimes. So I'm looking for an alternative command (if there's any) or setup that can pause the console screen in visual studio and doesn't cause any discrepancy in other c++ compilers.
This problem only occurs when you launch a console program from a GUI. So there is a very simple cross-platform workaround -- run console programs from a console. If you want to make a program that runs well from a GUI, make a GUI program.
The other suggested workarounds are awful. Both getchar() and system("pause") interfere with any attempt to use the program as a filter or to redirect its input and output. It doesn't make sense to break a program so that it works "correctly" when used incorrectly.
u can use this method
after that u write the last code of your program(before return 0;) u can use for example ( cin >> x; ) command..
then the program will wait for u to enter new data. and u can see your answer in debugging program :D..
good luck with this trick :D
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
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()
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.