There's nothing inherently wrong with your code that makes the window close - you're running it in the wrong way to see your results.

I assume you're using some kind of windows machine. Open a command line (probably hidden under "Accessories" if I recall correctly- the last Win machine I used was XP, so things have probably moved around a bit since my day) and run the program from there.

That means that you will have to use the command "cd" to change directory to where the programme has been put, and then type the name of the programme. And then press enter. If you do not know the name of the programme, or you do not know where it is, you need to learn more about the tools you're using, but that's a different problem. If the idea of using a command line to change directory means nothing to you, you need to learn more about your operating system, but that's a different problem.

If you cannot do the above, you can alter your programme to make it wait at the end. There are many, many ways to do this. Here is one.

Code:
int z;
cout << "Press enter to finish.";
cin >> z;