是否可以在C中打印新行之前等待几秒钟?

App*_*sin 10 c time line

例如,我可以输入类似的东西

"Hello"
"This"
"Is"
"A"
"Test"
Run Code Online (Sandbox Code Playgroud)

每条新线之间间隔1秒?

谢谢,

Riv*_*asa 26

那么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;
}
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

这就是你在Windows和Linux上睡觉的方式!对于Windows,两种方法都应该有效.只需将#of秒的参数更改为您需要的参数,然后插入需要暂停的位置,就像在printf之后一样.另外,注意:当使用windows.h时,请记住S睡眠中的资本,也就是毫秒!(感谢Chris指出这一点)

  • 我还想提醒其他可能偶然发现此线程的人,请记住将 Sleep() 大写;!!! (3认同)
  • 我还需要在睡眠前执行“fflush(stdout)”,因为第一个 printf 是在函数调用后打印的 (2认同)

小智 5

不像 sleep() 那么优雅,但使用标准库:

/* data declaration */
time_t start, end;

/* ... */

/* wait 2.5 seconds */
time(&start);
do time(&end); while(difftime(end, start) <= 2.5);
Run Code Online (Sandbox Code Playgroud)

我将留给您找出、和 的正确标头 ( #include)以及它们的含义。这是乐趣的一部分。:-)time_ttime()difftime()

  • 您的建议**也**不必要地浪费了处理器周期。sleep() 或某些变体是正确的答案。 (3认同)