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

问题描述 投票:0回答:2

我有以下代码

#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”和空白换行符都不会显示,并且输出是预期的。

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

c unix gcc
2个回答
2
投票

您的

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")
来清除屏幕;对于这样一个简单的任务来说,开销太大了。您最好使用
tputs
包中的
ncurses
。但是,这也使用 terminfo 数据库,因此无论如何您都必须修复您的
TERM
设置。


0
投票

您可以将clear的输出发送到/dev/null 只需使用:clear>/dev/null

© www.soinside.com 2019 - 2024. All rights reserved.