1.弹幕显示
效果:
h
he
hel
hell
,
,
hello world
hello worl
hello wor
hello wo
,
,
he
h
重复上述循环
代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
int sleep(unsigned long x)
{
clock_t c1 = clock();//类型为算数类型
clock_t c2;//算数类型
do
{
if ((c2 = clock()) == (clock_t)-1)//判断是否获取成功
{
return 0;
}
} while (1000.0*(c2 - c1) / CLOCKS_PER_SEC < x);//判断转换为秒
return 1;
}
int main()
{
char name[] = "hello world";//需要打印的字符串
int len = strlen(name);//计算字符串长度
while (1)//注意循环判断始终为真,所以结束程序我们需要手动关闭
{
for (int i = 0; i < len; i++)//循环打印每个字符
{
putchar(name[i]);//putchar打印字符。
fflush(stdout);//输出缓冲区。
sleep(500);//每个字节打印停顿
}
for (int i = 0; i < len; i++)
{
printf("\b \b");//转义字符'\b'为退格符
fflush(stdout);//输出缓冲区
sleep(500);//每次删除字节后停顿。
}
}
return 0;
}
2.从右像左滚动弹幕
效果:
hello world
ello world h
llo world he
lo world hel
o world hell
world hello
orld hello w
rld hello wo
ld hello wor
d hello worl
hello world
代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
int sleep(unsigned long x)
{
clock_t c1 = clock();//类型为算数类型
clock_t c2;
do
{
if ((c2 = clock()) == (clock_t)-1)//判断是否获取成功
{
return 0;
}
} while (1000.0*(c2 - c1) / CLOCKS_PER_SEC < x);//判断转换为秒
return 1;
}
int main()
{
int i = 0;
int cnt = 0;//第几个字符在最前面显示
char name[] = " hello world ";//为了美观适量的加入了空格。
int len = strlen(name);//计算数组长度
while (1)
{
putchar('\r');//转义字符'\r'将光标移动到本行开头
for (int i = 0; i < len; i++)
{
if (cnt + i < len)//这个if与else语句自己调试跟着看一遍就能明白
{
putchar(name[cnt + i]);
}
else
{
putchar(name[cnt + i - len]);
}
}
fflush(stdout);//输出缓冲区
sleep(500);//停顿
if (cnt < len - 1)
{
cnt++;
}
else
{
cnt = 0;
}
}
return 0;
}