2011-06-03 211 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(),但這不是很方便:/

相關問題