I just started learning C++ and I wrote this sample program from the text and when I compile and run it, it just closes after the user inputs any number and presses enter.
The program closes because there's nothing more for the program to do. It outputs the final statements really really fast and then reaches return 0
which causes it to exit. You'll want to do something there to pause the program.
On Windows, a basic way to do that is system("pause");
(you will need #include <stdlib.h>
)
cin.getline
is a more standard way to do it.
The program you posted has an error. I was not able to compile what you posted.
cout << "Hello Reader.\n"
<< "Welcome to C++.\n"
is not terminated with a semicolon. I added a semicolon and it compiles and runs as you expect.
Edit: Of course, you have to run the program in a terminal that stays open after the program exits, or use cin to wait for more input, or something like that.
Either put another read from cin
to wait for the user, or open the Command Prompt yourself and run it there.
Your program ends right after you print out your text. If you want to see anything on the screen you can add a cin
right before your return 0
so your program waits for a user response before exiting.
// Wait for user to hit enter
cin >> dummyVar;
return 0;
It closes because the execution reaches return 0;
and there is nothing left to do.
If you want the program to wait before closing you could add an something like this:
cout << "Press enter to exit...";
cin >> someVarThatWontBeUsed;
You could also run the program from the command line instead of running the .exe. It will reach end of execution anyway but the prompt will stay open.
After the user inputs a number, which is saved to numberOfLanguages
, it reaches return 0
which returns from the main
function and thus the program ends.