2012-06-06 28 views

回答

10

sleep()功能這麼做,有幾種方法來使用它;

在Linux上:

#include <stdio.h> 
#include <unistd.h> // notice this! you need it! 

int main(){ 
    printf("Hello,"); 
    sleep(5); // format is sleep(x); where x is # of seconds. 
    printf("World"); 
    return 0; 
} 

和Windows您可以使用DOS.H或WINDOWS.H這樣的:

#include <stdio.h> 
#include <windows.h> // notice this! you need it! (windows) 

int main(){ 
    printf("Hello,"); 
    Sleep(5); // format is Sleep(x); where x is # of milliseconds. 
    printf("World"); 
    return 0; 
} 

,或者您可以使用DOS.H用於Linux的風格像睡眠所以:

#include <stdio.h> 
#include <dos.h> // notice this! you need it! (windows) 

int main(){ 
    printf("Hello,"); 
    sleep(5); // format is sleep(x); where x is # of seconds. 
    printf("World"); 
    return 0; 
} 

這就是你如何睡在C和Windows上和Linux!對於Windows,這兩種方法都應該可以工只需將參數#秒改爲所需,然後插入任何需要暫停的地方,就像我之後的printf一樣。 此外,注意:在使用WINDOWS.H時,請記得在睡眠首都S,也那是它的毫秒! (感謝Chris指出了這一點)

+1

之前,我也想指出來誰可以在此線程絆倒別人,記得把握睡眠(); !!!! – AppleAssassin

+0

是的,否則編譯時會出錯。 – Annabelle

2

你可以看一下sleep()其掛起線程指定的秒數。

+0

正是我一直在循環進行,非常感謝 – AppleAssassin

1

的東西不一樣優雅的睡眠(),但使用標準庫:

/* data declaration */ 
time_t start, end; 

/* ... */ 

/* wait 2.5 seconds */ 
time(&start); 
do time(&end); while(difftime(end, start) <= 2.5); 

我將離開你的找出正確的頭(#include )爲time_ttime()difftime(),和他們的意思。這是樂趣的一部分。 :-)

+2

你的建議**也**不必要地浪費處理器週期。睡眠()或某些變體是正確的答案。 – pb2q

+0

哦,你說得對。不高雅(正如我已經說過的)。它只是便攜式。但浪費處理器週期不僅僅是一個副作用。實際上,這是代碼背後的主要思想,正如你所說的那樣,它的工作原理很笨拙。 :-) – CST

-2

適用於所有OS

int main() 
{ 
char* sent[5] ={"Hello ", "this ", "is ", "a ", "test."}; 
int i =0; 
while(i < 5) 
{ 
printf("%s", sent[i]); 
int c =0, i++; 
while(c++ < 1000000); // you can use sleep but for this you dont need #import 
} 
return 0; 
} 
+3

這是一個非常糟糕的做法。你的循環無用地浪費了處理器週期。爲什麼你應該反對使用'#import'來實現標準的睡眠功能?最糟糕的情況下,你需要#ifdef來覆蓋多個平臺。 – pb2q

+0

它只是一個選項,如果你sayits不好的做法,所以我花十年的時間沒有 – Eveler

+3

如果你不明白爲什麼這是一個糟糕的主意,那麼你應該瞭解爲什麼現在。 – pb2q

相關問題