gpt4 book ai didi

c - 在 C 程序中使用 system ("clear") 命令时出现奇怪的输出

转载 作者:行者123 更新时间:2023-11-30 19:35:20 24 4
gpt4 key购买 nike

我有以下代码

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>

#define dimensions 5

int RandomNumInRange(int M, int N)
{
return M + rand() / (RAND_MAX / (N - M + 1) + 1);
}

char ** CreateWorld(int dim)
{
int i,j;
char **world = malloc(dim *sizeof(char*));

for(i=0;i<dim;i++)
world[i]=malloc(dim*sizeof(char));

for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
world[i][j]=42;

return world;
}


void CreateCastle(char **world)
{

//assuming world is big enough
//to hold a match of 2
int randRow,randCol;

//1 to dimension -2 so we can spawn a 3x3 castle
randRow = RandomNumInRange(1,dimensions-2);
randCol = RandomNumInRange(1,dimensions-2);

printf("position: %d %d\n", randRow, randCol);
world[randRow][randCol]='c';
//fill the rest so castle is 3x3
//assuming there is enough space for that
world[randRow-1][randCol-1]=35;
world[randRow-1][randCol]=35;
world[randRow-1][randCol+1]=35;
world[randRow][randCol-1]=35;
world[randRow][randCol+1]=35;
world[randRow+1][randCol-1]=35;
world[randRow+1][randCol]=35;
world[randRow+1][randCol+1]=35;

}


void DisplayWorld(char** world)
{
int i,j;
for(i=0;i<dimensions;i++)
{
for(j=0;j<dimensions;j++)
{
printf("%c",world[i][j]);
}
printf("\n");
}
}

int main(void){

system("clear");


int i,j;
srand (time(NULL));


char **world = CreateWorld(dimensions);
DisplayWorld(world);
CreateCastle(world);

printf("Castle Positions:\n");
DisplayWorld(world);

//free allocated memory
free(world);

//3 star strats

char ***world1 = malloc(3 *sizeof(char**));

for(i=0;i<3;i++)
world1[i]=malloc(3*sizeof(char*));

for(i=0;i<3;i++)
for(j=0;j<3;j++)
world1[i][j]="\u254B";

for(i=0;i<3;i++){
for(j=0;j<3;j++)
printf("%s",world1[i][j]);
puts("");
}
free(world1);
//end
return 0 ;
}

如果我使用system("clear")命令,我会得到一行由“[3;J”组成的行接下来是预期的输出。如果我再次运行该程序,我会得到相同的乱码,然后是许多空白换行符,然后是预期的输出。如果我将 system("clear") 命令放在注释中,则“[3;J”和空白换行符都不会显示,并且输出是预期的。

编辑:看来错误不在代码中,而是在我系统上的终端设置(未)设置的方式中。感谢大家的意见,我现在确实有很多有趣的东西需要阅读和学习。

最佳答案

您的 clear 命令发送的代码似乎与 Gnome 终端模拟器不兼容,我相信您将使用该模拟器。

清除控制台的常规控制代码是CSI H CSI J。 (CSI 是控制序列初始值设定项:转义字符 \033 后跟 [)。 CSI H 将光标发送到起始位置,CSI J 从光标位置清除到屏幕末尾。您还可以使用 CSI 2 J 来清除整个屏幕。

在 Linux 控制台和某些终端仿真器上,您可以使用 CSI 3 J 来清除整个屏幕和回滚。我认为这样做很不友好(我的系统上安装的clear命令则不然。)

CSI 序列通常可以包含分号来分隔数字参数。然而,J 命令不接受多个数字参数,而且分号似乎会导致 Gnome 终端无法识别控制序列。无论如何,我不相信 Gnome 终端支持 CSI 3 J

clear 命令通常使用 terminfo 数据库来查找终端的正确控制序列。它使用 TERM 环境变量的值来标识终端,这表明您必须为该变量设置错误的值。尝试设置 export TERM=xterm 并查看是否得到不同的结果。如果可行,您必须找出 Linux Mint 配置环境变量的位置并修复它。

总的来说,您不需要使用system("clear")来清除屏幕;对于这样一个简单的任务来说,开销太大了。您最好使用 ncurses 包中的 tputs。但是,这也使用 terminfo 数据库,因此无论如何您都必须修复 TERM 设置。

关于c - 在 C 程序中使用 system ("clear") 命令时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42794954/

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