I am learning C++ through a book called C++ A Beginners Guide Second Edition. When I run the executable, It displays it for half a second and closes it.
I am using Microsoft Visual Studio Express 2013 for Windows Desktop on Windows 8.1.
Here is the code:
*/
#include <iostream>
using namespace std;
int main()
{
cout << "C++ is power programming.";
return 0;
}
I can only just see the text when I run, as the console closes so quickly.
Why does the program close so fast, and how do I stop that from happening?
'Project1.exe' (Win32): Loaded 'C:\Users\Benjamin\Documents\Visual Studio 2013\Projects\Project1\Debug\Project1.exe'. Symbols loaded.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp120d.dll'. Cannot find or open the PDB file.
'Project1.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Cannot find or open the PDB file.
The program '[6908] Project1.exe' has exited with code 0 (0x0).
Going through your program line by line:
int main()
{
This defines the entry point for your program, and the int
that it returns will be returned to whatever started the program.
std::cout << "C++ is power programming."; // or just cout when you're using namespace std
This prints the string literal C++ is power programming.
to the console.
return 0;
}
Returning a value of 0 to the caller is often used to indicate success (the program executed successfully). You could however, return something else if you wanted to (for example, if your program computes some value that should be used by the caller).
So, in a nutshell, you tell your program to print a message to the console and then return, which is exactly what it does. If you wanted to stop the program from closing as soon as it's finished, you could something just before the return 0
statement like this:
std::cin.get(); // or just cin.get() when using namespace std
return 0;
What std::cin.get()
does is wait for user input; pressing enter should end your program when you're ready.