How to keep alive a program in C++?
I'm using Visual C++ 2010 Express
and I just started learning C++
.
So when I want to run开发者_JAVA技巧 this code:
#include <iostream>
using namespace std;
int main(){
cout << "Hello World! ";
return 0;
}
It works, but the program exits immediately after I started it, how should I keep the program alive?
In Visual studio you have two options to run a program. There is absolutely no need to modify your code as many other posts are suggesting.
1) Run with debugging. You are probably using this, and to make it stop 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 before the window closes.
If it's just to read the output, you don't need the program to stay "alive", just run it from a command prompt window and the output will remain visible. You can also use a debugger to break execution at a particular point.
There are plenty of ways, good and bad, to do it 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, even though this is a Bad Idea:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World! ";
while (true) { }
return 0;
}
What are you trying to accomplish?
Edited to note that infinite loops are bad, even though they'll technically keep the program alive forever.
system("Pause");
"Press any key to continue..."
Someone who is familiar with windows console app developing will be able to help you better, until then try this:
#include <iostream>
int main(){
std::cout << "Hello World! ";
std::cin.get(); // waits for input, press enter to continue
return 0;
}
Reference for std::cin.get()
cout<<"Please press any key to quit";
char number;
cin>>number;
First off, you probably want to add a newline output to flush this to the console.
cout << "Hello World! " << endl;
If you really don't want to exit right away, you could wait for console input using cin
after you write this out, or call Sleep(10000)
for a 10 second delay and so on.
Set breakpoint at the end of main function.
精彩评论