2017-09-15 153 views
0

我想添加一個延遲,這樣一條線將會運行,然後在短暫的延遲之後,第二個會運行。我對C++相當陌生,所以我不確定我會怎麼做。所以最好在下面的代碼中打印「Loading ...」並等待至少1-2秒,然後再次打印「Loading ...」。目前它可以即時打印而不是等待。如何在C++中添加延遲代碼。

cout << "Loading..." << endl; 
// The delay would be between these two lines. 
cout << "Loading..." << endl; 
+0

你忘了提到操作系統。在linux上,你可以使用unistd函數:'sleep(2)'? – Serge

+3

哪個版本的C++?我寧願使用'std :: this_thread :: sleep_for(std :: chrono :: seconds(2))'... – whoan

+0

我正在使用C++ 11。 –

回答

6

++ 11你可以使用這個線程和CRONO做到這一點:

#include <chrono> 
#include <thread> 
... 
using namespace std::chrono_literals; 
... 
std::this_thread::sleep_for(2s); 
+0

不錯,乾淨,標準。但是在使用時間字面值之前,你需要添加'using namespace std :: chrono_literals'。 – Patrick

+0

@帕特里克謝謝,我只是把它添加到答案。 – Serge

-1

你想從unistd.hsleep(unsigned int seconds)功能。在cout語句之間調用此函數。

在C
+0

'unistd.h'是POSIX,而不是C++。 – Barmar

+0

這是完全正確的,但是這對他來說可能會更簡單。 – Saustin

+3

這不是標準的C++。標準庫中有一個非常好的睡眠功能。本質上,'this_thread :: sleep_for(2s);'。 –

0

在WINDONS OS

#include <windows.h> 
Sleep(sometime_in_millisecs); // note uppercase S 

在Unix中的基本操作系統

#include <unistd.h> 
unsigned int sleep(unsigned int seconds); 

#include <unistd.h> 
int usleep(useconds_t usec); // Note usleep - suspend execution for microsecond intervals 
0

模擬「正在進行的報告「,您可能會考慮:

// start thread to do some work 
m_thread = std::thread(work, std::ref(*this)); 

// work-in-progress report 
std::cout << "\n\n ... " << std::flush; 
for (int i=0; i<10; ++i) // for 10 seconds 
{ 
    std::this_thread::sleep_for(1s); // 
    std::cout << (9-i) << '_' << std::flush; // count-down 
} 

m_work = false; // command thread to end 
m_thread.join(); // wait for it to end 

隨着輸出:10175240之後

... 9_8_7_6_5_4_3_2_1_0_

工作拋棄了我們

概述:本方法 '工作' 沒有 '完成',但收到的命令放棄操作並在超時退出。 (成功測試)

該代碼使用chrono和chrono_literals。