c++ccommandargument

Using System("pause") when Command Arguments have been set to a data file


I'm currently writing a very simple program for a class, and am quickly realizing that I never really knew what the System("pause") command was doing.

The prompt for the program demands that I have the Command Arguments (located in Debug->Properties->Configuration Properties->Debugging in Visual Studio 2013) set to an input file so that I can read from the file using "cin". After setting this property, however, I've noticed that the familiar System("pause") command no longer works to keep the console window open. (I changed the property back to its default and it worked again, so this seems to be the problem.)

Any explanations? I'm really curious as to what System("pause") is really doing in the background now.


Solution

  • The system function on Windows launches an instance of cmd.exe and asks it to execute the command you pass, which is pause in this case. Normally cmd.exe would wait for the user to press a key. In other words, it reads one character from the standard input device and returns immediately once it reads it. Well, you gave it a file as the standard input device, so it reads one character from that file and returns immediately.

    It's doing exactly what you asked it to do. There's nothing mysterious going on in the background.

    You can demonstrate this easily by just entering pause < foo at the command line, where foo is any file. You'll see that pause returns immediately in that case.

    And as David Schwartz points out in comments, using system("pause") is a horrible practice. If you need to wait for user input to continue, do it yourself with a simple pair of cout and cin calls.