2010-11-12 52 views

回答

14

使用boost::this_thread::sleep

// sleep for 5 seconds 
boost::this_thread::sleep(boost::posix_time::seconds(5)); 
+0

雖然,當然,提升可能不是這個人的選擇。 – Omnifarious 2010-11-12 04:29:59

+0

+1。從我的手指中拿出話語。 – 2010-11-12 04:32:13

+7

@Omnifarious:這是可能的。但除非OP另有具體說明,否則我認爲沒有理由認爲提振不是一種選擇。如果可能的話,每個C++開發者都應該安裝boost。 – 2010-11-12 04:32:38

1

我不知道任何便攜功能,但主流操作系統對於* nix有usleep,對於Windows有Sleep

+3

boost對於便攜式的許多定義而言是「便攜」的。 – Omnifarious 2010-11-12 04:30:29

0

請注意,上面上的代碼:: Blocks的12.11和Visual Studio測試代碼2012
在Windows 7

迫使你的程序停止或等待,你有幾種選擇:


  • 睡眠(無符號整數)

該值必須是以毫秒爲單位的正整數。 這意味着,如果你希望你的程序等待2秒鐘,進入2000年

下面是一個例子:

#include <iostream>  //for using cout 
#include <stdlib.h>  //for using the function sleep 

using namespace std; //for using cout 

int main(void)   
{ 
    cout << "test" << endl; 
    sleep(5000);   //make the programme waiting for 5 secondes 
    cout << "test" << endl; 
    sleep(2000);   // wait for 2 secondes before closing 

    return 0; 
} 

如果等待時間過長,這可能意味着該參數是排在第二。所以改變這樣的:

sleep(5); 

對於那些誰得到使用睡眠嘗試通過_sleep或睡眠來取代它尤其在代碼:: Bloks的錯誤信息或問題。
如果你仍然有問題,嘗試添加一個這個庫的代碼biggining。

#include <stdio.h> 
#include <time.h> 
#include <unistd.h> 
#include <dos.h> 
#include <windows.h> 

  • 系統( 「暫停」)

一個簡單的 「Hello world」 在Windows控制檯應用程序可能會結束前,你可以看到什麼。那種情況下你可以使用系統(「暫停」)。

#include <iostream>  

using namespace std; 

int main(void)   
{ 
    cout << "Hello world!" << endl; 

    system("PAUSE"); 

    return 0; 
} 

如果您收到消息「錯誤:‘系統’並沒有在這一範圍內聲明」只是在代碼的biggining添加 以下行:

#include <cstdlib> 

  • cin。忽略()

同樣的結果可以通過使用cin.ignore()達到:

#include <iostream>  

using namespace std;  

int main(void)   
{ 
    cout << "Hello world!" << endl; 

    cin.ignore(); 

    return 0; 
} 

  • cin.get()

示例:

#include <iostream>  

using namespace std;  

int main(void)   
{ 
    cout << "Hello world!" << endl; 

    cin.get(); 

    return 0; 
} 

  • 的getch()

只是不要忘了添加庫CONIO.H:

#include <iostream>  
#include <conio.h> //for using the function getch() 

using namespace std;  

int main(void) 
{ 

    cout << "Hello world!" << endl; 

    getch(); 

    return 0; 
} 

你可以有消息告訴你使用_getch( )insted of getch