2010-11-12 53 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