24

例如,我可以让它输入类似

"Hello"
"This"
"Is"
"A"
"Test"

每条新线之间有 1 秒的间隔?

谢谢,

4

4 回答 4

45

好吧,sleep()功能做到了,有几种使用方法;

在 Linux 上:

#include <stdio.h>
#include <unistd.h> // notice this! you need it!

int main(){
    printf("Hello,");
    sleep(5); // format is sleep(x); where x is # of seconds.
    printf("World");
    return 0;
}

在 Windows 上,您可以像这样使用 dos.h 或 windows.h:

#include <stdio.h>
#include <windows.h> // notice this! you need it! (windows)

int main(){
    printf("Hello,");
    Sleep(5); // format is Sleep(x); where x is # of milliseconds.
    printf("World");
    return 0;
}

或者您可以将 dos.h 用于 linux 风格的睡眠,如下所示:

#include <stdio.h>
#include <dos.h> // notice this! you need it! (windows)

int main(){
    printf("Hello,");
    sleep(5); // format is sleep(x); where x is # of seconds.
    printf("World");
    return 0;
}

这就是你在 Windows 和 linux 上都睡在 C 中的方式!对于 Windows,这两种方法都应该有效。只需将 # of seconds 的参数更改为您需要的参数,然后在需要暂停的地方插入,就像我一样在 printf 之后。另外,注意:使用windows.h时,请记住Ssleep中的大写,也就是毫秒!(感谢克里斯指出这一点)

于 2012-06-06T22:14:46.927 回答
4

不如 sleep() 优雅的东西,但使用标准库:

/* data declaration */
time_t start, end;

/* ... */

/* wait 2.5 seconds */
time(&start);
do time(&end); while(difftime(end, start) <= 2.5);

我将为您找出正确的标题 ( #include)和time_t,以及它们的含义。这是乐趣的一部分。:-)time()difftime()

于 2012-06-06T22:19:10.163 回答
2

您可以查看将线程挂起指定秒数的sleep() 。

于 2012-06-06T22:06:27.303 回答
-7

适用于所有操作系统

int main()
{
char* sent[5] ={"Hello ", "this ", "is ", "a ", "test."};
int i =0;
while( i < 5 )
{
printf("%s", sent[i] );
int c =0, i++;
while( c++ < 1000000 ); // you can use sleep but for this you dont need #import
} 
return 0;
}
于 2012-06-06T22:25:21.190 回答