2010-02-12 27 views

回答

20
#include <windows.h> 

Sleep(number of milliseconds); 

或者如果您想在等待其他程序时暂停程序,请使用WaitForSingleObject

+0

错误错误C3861:'Sleep':找不到标识符 //尽管#include 2010-02-12 14:36:25

+0

您可以发布您的代码以及您使用的是哪种编译器?这可以在我的机器上使用GCC:#include int main() { Sleep(1000); } – IVlad 2010-02-12 14:44:38

+0

好吧,你必须有现代的等先排队和老年后,这是一个规则?至少它与那个订单一起工作。 – 2010-02-12 14:50:52

7

如果您正在使用升压,您可以使用thread::sleep功能:

#include <boost/thread/thread.hpp> 
boost::system_time time = boost::get_system_time(); 
time += boost::posix_time::seconds(1); 
boost::thread::sleep(time); 

否则,你将不得不使用Win32 API:

#include <windows.h> 
Sleep(1000); 

,显然,C + + 0x包括:

#include <thread> 
std::this_thread::sleep_for(chrono::seconds(1)); 
+0

我的天哪,最后一行很丑。 – 2010-02-12 20:48:34

+0

@Steve:我的歉意。 – 2010-02-12 21:20:47

+1

我不怪你,除非你在C++标准委员会;-) – 2010-02-13 02:03:03

1

如果您希望程序在“暂停”时保持响应状态,编辑使用计时器事件。

+0

实际上,在Qt中,如果你希望你的程序在从主线程执行的一段代码暂停时作出响应,你不要你的计时器的超时事件发生在主线程中。 – 2010-02-24 15:22:56

0

这取决于您正在编写什么类型的程序。

控制台应用程序可以调用睡眠。一个GUI应用程序可能不是想要这样做,因为所有的菜单和小部件都会变得不敏感,并且在此期间该应用程序不会重绘。相反,你需要做一些事情,比如设置一个带有回调的计时器。

0

如果您正在使用的框架未提供睡眠功能,请不要在GUI中使用睡眠功能。这可能会给数据创建引用问题(特别是在不是主线程的线程中)。这可能会冻结你的GUI。它不仅仅是一个短时间睡眠的问题,如果您需要这样做,请使用waitmutexes。

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.ignore()

同样的结果可以通过使用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的残培的

1

在C++ 11中,您可以使用标准库工具来执行此操作:

#include <chrono> 
#include <thread> 
std::this_thread::sleep_for(std::chrono::milliseconds(x));