2016-10-09 27 views
0

我有以下代碼:爲什麼發生異常時不顯示整數?

int main() 
{ 
    int i = 0; 
    cout << i; //why is i not printed even though it is before the exception? 
    int j = 1/i; //divide by 0 
    j++; 
    cout << i << j; 
    return 0; 
} 

爲什麼i不打印?它應該被打印,因爲它在異常發生之前。

但沒有打印,我只是得到例外。

任何想法?

+0

[除以0的除法不會引發異常](http://stackoverflow.com/questions/6121623/catching-exception-divide-by-zero)。所以程序很可能會運行完成,你會看到輸出。 – PaulMcKenzie

回答

3

這可能是因爲流不刷新。在某些平臺上,每次輸出後都會刷新,但在其他平臺上則不是。

所以,如果你衝它,你會得到0作爲輸出:

cout << i << flush; // 'flush' flushes the stream = displays everything immediately 
-1

我覺得你可以參考這個功能puts(s),你可以這樣寫樣本:

int main() 
{ 
    char a[20]; 
    int b = 1; 
    while(b>10) 
    { 
     gets(a); 
     puts(a); 
     b++; 
    } 
    return 1; 
} 

你會發現它們在所有輸入完成後輸出,因此輸出具有緩衝區。

+0

'puts'與它有什麼關係? –

相關問題