Here's a question that I don't quite understand:
The command, system("pause");
is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees.
Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it.
I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don't understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all?
What are your thoughts on this subject?
For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.
One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.
You can use
std::cin.get()
fromiostream
:Besides,
system('pause')
is slow, and includes a file you probably don't need:stdlib.h
. It is platform-dependent, and actually calls up a 'virtual' OS.Because it is not portable.
is a windows / dos only program, so this your code won't run on linux. Moreover,
system
is not generally regarded as a very good way to call another program - it is usually better to useCreateProcess
orfork
or something similar.It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
Bodging in System("pause") runs the Windows command-line "pause" program and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.
A better idea would be to put a breakpoint at the end and debug it, but that again has problems.
a simple getchar() should do just fine.
Here's one reason you shouldn't use it: it's going to piss off most anti-virus programs running on Windows if you're passing the program over to another machine because it's a security threat. Even if your program only consists of a simple
cout << "hello world\n"; system("pause");
It's resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.