原因:IDE (如 Visual Studio、Code::Blocks) 啟動主控台子進程,進程結束後視窗自動關閉。
| 方法 | 程式碼 | 優點 | 缺點 |
|---|---|---|---|
getchar() | getchar(); | 標準 C、跨平台 | 若輸入緩衝區殘留換行需雙呼叫 |
system("pause") | system("pause"); | Windows 專用、提示訊息友善 | 非標準、效能差、安全風險 |
| IDE 設定 | VS: 專案屬性 → Linker → System → SubSystem: Console (/SUBSYSTEM:CONSOLE) + 「Start without debugging」 | 無侵入代碼 | 依賴特定 IDE |
getchar()int main()
{
// ... 程式邏輯 ...
printf("Press Enter to exit...");
while (getchar() != '\n'); // 清空殘留換行
getchar(); // 等待使用者按 Enter
return 0;
}
return 0; 之前?getchar() 會阻塞等待輸入,放在程式邏輯之後、return 之前,確保使用者能看見輸出結果再按鍵退出。放在迴圈內或函數開頭會提前阻塞,導致邏輯無法執行。