2015-10-10 16 views
4

終止/退出主函數的D方式是什麼?D:如何退出主界面?

import std.stdio; 
import core.thread; 

void main() 
{ 
    int i; 
    while (i <= 5) 
    { 
     writeln(i++); 
     core.thread.Thread.sleep(dur!("seconds")(1)); 
    } 
    if (i == 5) 
    { 
     writeln("Exit"); 
     return; // I need terminate main, but it's look like break do exit only from scope 
    } 
    readln(); // it's still wait a user input, but I need exit from App in previous step 
} 

我試着谷歌上搜索,發現一個問題D exit statement 有建議用C退出功能。現代D中是否有任何新的未來,允許它更優雅?

+5

return語句在代碼中你main()功能然後像

int main(string[] args) { try { // Your code here } catch (ExitException e) { return e.rc; } return 0; } 

在點你代碼將退出程序。你有的問題是邏輯之一 - 當while循環終止時,我== 6,而不是5. –

+0

@ AdamD.Ruppe,哦,你是對的,有什麼方法可以修復它在while循環,或只有可能的修復是'if(i == 6)'? –

+0

正如亞當所說的'if(i == 5)'總是錯誤的。如果你想執行if分支,你可以寫'if(i == 6)'。或者你是否打算在循環內部添加「if」?後增值操作符的使用會改變程序的輸出,但它仍然以'i == 6'退出循環。 –

回答

3

導入STDLIB並調用exit而通過0

import std.c.stdlib; 
    exit(0); 
+1

雖然不能運行終結器。 –

4

如果你沒有做一個緊急出口,然後要清理一切。我爲此目的創建的ExitException

class ExitException : Exception 
{ 
    int rc; 

    @safe pure nothrow this(int rc, string file = __FILE__, size_t line = __LINE__) 
    { 
     super(null, file, line); 
     this.rc = rc; 
    } 
} 

你在哪裏,你需要退出你打電話

throw new ExitException(1);