How to save a program in C ++?

I am using Visual C++ 2010 Express , and I just started learning C++ .

So, when I want to run this code:

 #include <iostream> using namespace std; int main(){ cout << "Hello World! "; return 0; } 

It works, but the program comes out right after I started it, how can I keep the program alive?

+4
source share
7 answers

If this is just for reading the output, you do not need the program to remain β€œlive”, just run it from the command window and the output will remain visible. You can also use the debugger to interrupt execution at a specific point.

There are many ways, good and bad, to do this with code:

 #include <iostream> using namespace std; int main() { cout << "Hello World! "; cin.get(); // Wait for some input, as suggested by PigBen return 0; } 

or

 #include <iostream> using namespace std; int main() { cout << "Hello World! "; Sleep(1000); // one second return 0; } 

or, although this is a bad idea:

 #include <iostream> using namespace std; int main() { cout << "Hello World! "; while (true) { } return 0; } 

What are you trying to achieve?

Edited to notice that endless loops are bad, although they technically support the program forever.

+5
source

In Visual Studio, you have two options for running the program. There is absolutely no need to change your code, like many other messages.

1) Run with debugging. You are probably using this, and to stop it anywhere you need to set a breakpoint.

2) Run without debugging. This should leave the console window open and prompt you to press a key until the window closes.

+7
source
 system("Pause"); 

"Press any key to continue ..."

+5
source

Someone familiar with the development of the Windows console application will be able to help you until you try this:

 #include <iostream> int main(){ std::cout << "Hello World! "; std::cin.get(); // waits for input, press enter to continue return 0; } 

Link to std :: cin.get ()

+2
source
 cout<<"Please press any key to quit"; char number; cin>>number; 
+1
source

First, you probably want to add newline output to clear it from the console.

 cout << "Hello World! " << endl; 

If you really do not want to leave immediately, you can wait for the console to be entered using cin after recording it or call Sleep(10000) for a delay of 10 seconds, etc.

+1
source

Set a breakpoint at the end of the main function.

+1
source

All Articles