IDE (Visual Studio、Dev-C++、Code::Blocks) 或雙擊 exe 運行時,控制台視窗屬於子進程。main 返回後進程結束,視窗隨即關閉,導致輸出結果來不及查看。
#include <stdlib.h> // system()
int main() {
// 你的代碼...
printf("結果: %d\n", result);
system("pause"); // Windows 專用,調用 cmd.exe /c pause
return 0;
}
return 0; 之前。| 方法 | 代碼 | 優點 | 缺點 |
|---|---|---|---|
標準 C getchar() | printf("按 Enter 退出..."); getchar(); | 標準庫、無依賴 | 若緩衝區殘留換行需雙 getchar() |
| 循環等待 | while (getchar() != '\n'); getchar(); | 清空緩衝區 | 略顯繁瑣 |
C++ cin.get() | std::cin.get(); | C++ 風格 | 需 <iostream> |
| Windows API | system("pause"); | 提示友好 | 非標準、啟動進程開銷 |
| Linux/macOS | system("read -p 'Press Enter...'"); | 跨平台腳本 | 依賴 shell |
Console (/SUBSYSTEM:CONSOLE) + 調試 → 「自動關閉主控台視窗」取消勾選。launch.json 添加 "externalConsole": true 或 "console": "externalTerminal"。system("pause"),僅用於學習/測試主程式。system() 存在命令注入風險,參數不可來自用戶輸入。pause 會導致掛起,需檢測 isatty(fileno(stdin))。getchar() 兼容性最好。核心思想:控制台視窗生命週期 = 進程生命週期,要么延長進程(等待輸入),要么讓視窗不依賴進程(IDE 外部終端)。