C语言中优雅的文本动画
Elegant Text Animation in C
有什么方法可以在 C 中为文本输出设置动画吗?我对编程比较陌生,正在尝试完成类似于 python 代码的一些事情,但一直无法在网上找到任何东西。欢迎所有见解。感谢阅读。
#python text animation
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.02)
delay_print("hello world")
这是一个例子:
#include <stdio.h>
#include <unistd.h>
void delay_print(char *str)
{
for (char *p = str; *p; p++) {
putchar(*p);
fflush(stdout);
usleep(20000);
}
putchar('\n');
}
int main(void)
{
delay_print("Hello world!")
return 0;
}
这是一个跨平台示例,几乎可以在任何平台上运行 OS:
#include <stdio.h>
// check if being compiled for windows or posix (linux/bsd/mac)
#ifdef _WIN32
// include minimal windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
// include posix headers
#include <time.h>
#endif
void milli_sleep(unsigned int milliseconds);
void delay_print(char* str, unsigned int milliseconds);
int main()
{
delay_print("Hello World\n", 20); // 20 milliseconds = 0.02 seconds
return 0;
}
void delay_print(char* str, unsigned int milliseconds)
{
for (; *str; str++) {
putchar(*str);
fflush(stdout);
milli_sleep(milliseconds);
}
}
void milli_sleep(unsigned int milliseconds)
{
#ifdef _WIN32
// use windos Sleep function, sleeps for a number of milliseconds
Sleep(milliseconds);
#else
// use posix nanosleep function, sleeps for a number of nanoseconds
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000L;
nanosleep(&ts, NULL);
#endif
}
有什么方法可以在 C 中为文本输出设置动画吗?我对编程比较陌生,正在尝试完成类似于 python 代码的一些事情,但一直无法在网上找到任何东西。欢迎所有见解。感谢阅读。
#python text animation
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.02)
delay_print("hello world")
这是一个例子:
#include <stdio.h>
#include <unistd.h>
void delay_print(char *str)
{
for (char *p = str; *p; p++) {
putchar(*p);
fflush(stdout);
usleep(20000);
}
putchar('\n');
}
int main(void)
{
delay_print("Hello world!")
return 0;
}
这是一个跨平台示例,几乎可以在任何平台上运行 OS:
#include <stdio.h>
// check if being compiled for windows or posix (linux/bsd/mac)
#ifdef _WIN32
// include minimal windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
// include posix headers
#include <time.h>
#endif
void milli_sleep(unsigned int milliseconds);
void delay_print(char* str, unsigned int milliseconds);
int main()
{
delay_print("Hello World\n", 20); // 20 milliseconds = 0.02 seconds
return 0;
}
void delay_print(char* str, unsigned int milliseconds)
{
for (; *str; str++) {
putchar(*str);
fflush(stdout);
milli_sleep(milliseconds);
}
}
void milli_sleep(unsigned int milliseconds)
{
#ifdef _WIN32
// use windos Sleep function, sleeps for a number of milliseconds
Sleep(milliseconds);
#else
// use posix nanosleep function, sleeps for a number of nanoseconds
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000L;
nanosleep(&ts, NULL);
#endif
}