2017-09-15 154 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。