问题
I am a beginner in C++ and I was trying to write a program that finds the average of two numbers, but when I run the program, the window disappears without allowing me to see the result. Can someone please help me? Thanks
#include <iostream>
using namespace std;
int main()
{
int number1,number2,answer;
cout << "number1? ";
cin >> number1;
cout << "number2? ";
cin >> number2;
answer = (number1 + number2)/2;
cout << answer<<endl;
return 0;
}
回答1:
Solution #0 (proper):
Run program from shell (cmd.exe
, bash
)
Solution #1 (proper):
Run program from orthodox file manager. Far Manager or midnight commander.
Solution #2 (alternative);
Redirect output to file. program.exe >file.txt
from command line.
Solution #3 (improper):
Launch message box, use "sleep"/"Sleep" to delay program termination.
Solution #4 (improper):
Request user input at the end of program.
Solution #5 (improper):
Set breakpoint on "return 0", debug the program.
Solution #6 (windows+msvc):
Launch program from msvc by Ctrl+F5 using debug build. You'll get "press key to continue" prompt.
回答2:
Put a breakpoint at your return
statement. It won't stop on an uncaught exception but that can be fixed with a try
/catch
block at the outermost part of main
.
回答3:
Before you return add system("PAUSE"); and this should fix your problem.
回答4:
If you are using Visual Studio, hit CTRL+F5 to run. That inserts a "Hit RETURN to continue" for a console application.
回答5:
Include this header:
#include <stdio.h>
And add a call to getchar()
before you return
:
cout << answer<<endl;
getchar(); // wait for user input
return 0;
回答6:
Solution #6 from SigTerm (above) is not guaranteed to work. In Visual Studio you should right-click your project and choose:
Properties | Configuration Properties | Linker | System | SubSystem
and in the dropdown choose Console (/SUBSYSTEM:CONSOLE).
回答7:
I always hated that...I always find the easiest to be system("pause");
right before you return, but that's not a portable solution (cin.get is though). There are many other ways as well, some of which are mentioned in the link below.
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787
Edit: system("pause");
is terrible, should never be used, and may or may not end life on this planet as we know it, even if by a beginner in a project called 'Hello'. Using system("pause")
is expensive and dangerous, and if you use it, you'll never see anyone you love again. Don't do it. Use cin.get
or something else.
来源:https://stackoverflow.com/questions/9436108/c-beginner-execution-window-disappears-quickly