2011-06-03 188 views
0

可能重复:
How to stop C++ console application from exiting immediately?控制台程序退出

我有以下控制台程序:

#include <iostream> 
using namespace std; 

int main() 
{ 
    int a; 
    int b; 


cout<<"Enter a"; 
cin>>a; 

cout<<"Enter b"; 
cin>>b; 

int result = a*b; 

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl; 
    return 0; 
} 

一旦我运行程序,它接受输入,但退出在我能看看结果之前。我需要为程序做些什么才能退出,然后才能看看在结果?

+1

您使用的是什么环境? – 2011-06-03 12:10:38

+0

Qt创建者4.7。 – Gandalf 2011-06-03 12:15:01

+0

您可以随时查看结果。只需捕获输出或从现有控制台运行即可。 – 2011-06-03 12:19:12

回答

1

如何在return 0;声明之前添加system ("pause");

+0

构建问题:'system'未在此范围内声明 – Gandalf 2011-06-03 12:14:34

+0

'#include '将为您声明'system'。但是,最好找出如何让你的环境在程序退出后保持控制台打开状态。 – 2011-06-03 12:16:16

1

使用getche(),getch()或任何基于字符的输入函数。

int main() 
{ 
    int a; 
    int b; 
    int result = a*b; 

cout<<"Enter a"; 
cin>>a; 

cout<<"Enter b"; 
cin>>b; 

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl; 
getch(); //use this.It would wait for a character to input. 
return 0; 
} 

而且一般我们使用Enter退出的ASCII值由它。但因为它是没有用的,我们不会将其存储在一个变量中获取的程序。

1

你可以要求更多的反馈

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl; 

char stop; 
cin >> stop; 
2

顺便说一句,你已经计算出的result值,你已经得到了你的ab输入之前,这样的result值要么是0如果你的编译器会组装代码来初始化堆栈中声明的任何变量,或者只是一些随机值。事实上,你甚至不需要声明result ......你可以在cout声明中计算它的值。所以,你可以调整你的最后一行,所以它看起来是这样的:

cout << "You entered" << a <<"and you entered"<< b 
    << "Their product is" << (a*b) << endl; 

要退出停止该程序,你可以抓住另一个charstdin。所以,你可以做到以下几点:

cout << "Press any key to exit..." << endl; 
char extra; 
cin >> extra; 
0

的Windows:

//1 
    system ("pause"); 
//2 
    #include<conio.h> 
    _getch(); 

.NET(Windows)中:

总评:

#include <cstdlib.h> 
    return EXIT_SUCCESS; 
+0

我不知道''是(还是'_getch'),但我猜测它也只适用于Windows。在标准C++中,你需要''的'getchar()'或''的'cin.get()'。 – 2011-06-03 12:22:10

+0

_getch()在gcc中工作。 – Secko 2011-06-03 12:22:51

+0

@Secko:不是我的版本,它没有。标准函数将适用于任何符合要求的编译器。 – 2011-06-03 12:32:06

0

我喜欢在Windows上使用conio.h中的getch(),但这不是很方便:/