Friday, 24 February 2012

Keep Console App Window Open in Visual C++


Visual C++ allows you to create a “Win32 Console Application.” It’s like the days before Windows in DOS with the command prompt. If you start a new console app and run it, a window will pop up and close right away. That’s the console window. How do you keep the window form closing so you can see any output? I searched the web and people referred to using system(“pause”). They suggested I add this line of code before the return line in the main function. I tried it and it didn’t work. I received this compile error: C3861: 'system': identifier not found. What they failed to mention was to include the standard library <cstdlib> so the compiler can find the function. Once the include directive was included, the code worked.


Sample Code.

// The standard library includes system function.
#include <cstdlib>

int _tmain(int argc, _TCHAR* argv[])
{


// Pause to keep console window open.
system("pause");

     return 0;
}


The pause argument to the system function will display the message, “Press any key to continue…” and wait until a key is pressed before closing the window.





No comments:

Post a Comment