gpt4 book ai didi

c - 在 C 程序中使用 ANSI 代码

转载 作者:行者123 更新时间:2023-12-02 19:48:41 26 4
gpt4 key购买 nike

我制作了以下屏幕保护程序。我使用ANSI代码,用于清除终端屏幕并定义当前时间的位置。然而,多次打印相同的 ANSI 代码。例如行:

printf( "\e[%d;%df%s\n", random_line, random_column, ctime( &t1 ));

打印 -->

[0;-14fMon Jun 1 13:39:49 2015

我的代码是:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

int main( void )
{
int lines = 0, columns = 0, random_line = 0, random_column = 0;
time_t t1;
struct winsize w;

while( 1 )
{
printf( "\e[2J\n" );

ioctl( 0, TIOCGWINSZ, &w );
//printf( "Lines of Term: %d\n", w.ws_row );
//printf( "Columns of Term: %d\n", w.ws_col );
lines = w.ws_row;
columns = w.ws_col;

srand( time( NULL ) );
random_line = rand() % lines;
//printf( "Random Line = %d\n", random_line );
random_column = ( rand() % columns ) - 20;
//printf( "Random Column = %d\n", random_column );

t1 = time( NULL );
printf( "\e[%d;%df%s\n", random_line, random_column, ctime( &t1 ) );
sleep( 5 );
}

return ( 0 );
}

最佳答案

当您为行或列提供值时,ANSI 转义序列的格式不正确,这就是为什么您会看到类似以下内容的原因:

[0;-14fMon Jun 1 13:39:49 2015

而不是字符串:

Mon Jun 1 13:39:49 2015

位于某处。

基本上,ANSI 序列解释器不知道如何将光标放在屏幕最左侧左侧 14 个字符处,因此您可能应该重新考虑为什么要减去 20 从随机值中获取列。

如果要确保文本适合所选行而不换行到下一行,您应该使用(也更改值,因为日期字符串中有超过 20 个字符):

random_column = rand() % (columns - 25);

关于c - 在 C 程序中使用 ANSI 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30571632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com