初學者常會遇到這個問題,程式寫完了,但只有黑黑的畫面閃一下,接著什麼都看不到了。那是因為程式跑太快,所以你來不及看。這裡提供三個方式去解決。

假設原始碼為:

#include <stdio.h>
int main()
{
       printf("hello, world.\n");
       return 0;
}

1. 引入 stdlib.h ,在 return 0 前加入 system("pause");

#include <stdio.h>
#include <stdlib.h>
int main()
{
       printf("hello, world.\n");
       system("pause");
       return 0;
}

說明:這是調用命令提示字元 pause 的指令。

2. 直接在 return 0 之前加入 getchar();

#include <stdio.h>
int main()
{
       printf("hello, world.\n");
       getchar();
       return 0;
}

說明:簡單的說,當你按下 enter 的時候才會跳開 (意思是你按其它鍵的話還是會顯示在螢幕上),但注意的是,若程式碼中有任何之其他輸入函式,最後會因換行還留在 buffer 裡而導致失敗。

3. 引入 conio.h ,return 0 前加入 getch()

#include <stdio.h>
#include <conio.h>
int main()
{
       printf("hello, world.\n");
       getch();
       return 0;
}

說明:由於這個指令並非標準指令,只是大多的 complier 都有實做 (如果你找到有哪個 complier 沒這個指令請告知我),使用這個指令就相當於 "按下任意鍵離開"。

 

嚴格說來,目前沒有一個可攜性的作法,在 windows 作業系統裡,最常使用的是第一種作法。另也較建議,試著以命令提示字元方式執行該程式,總會有所收穫的。

arrow
arrow
    全站熱搜

    edisonx 發表在 痞客邦 留言(0) 人氣()