如何将光标移回C中的第一行?

时间:2015-11-12 17:49:25

标签: c cursor line

我是C的新手,这是我的代码。

{{1}}

这是我得到的输出。

enter image description here

有没有办法让第二张牌出现在第一张牌旁边? 感谢

2 个答案:

答案 0 :(得分:2)

如果您的终端支持它们,可以使用这些终端转义码来定位光标。

#include<stdio.h>

void printCard( int col, char name, char symbol);

int main()
{
    printf ( "\033[2J");//clear screen
    printCard( 0, 'J','*');
    printCard( 1, 'K','&');
    return 0;
}
void printCard(int col, char name, char symbol)
{
    printf ( "\033[1;%dH", col * 14);//move cursor line 1
    printf("-------------\n");
    printf ( "\033[2;%dH", col * 14);//move cursor line 2
    printf("| %c         |\n",name);
    printf ( "\033[3;%dH", col * 14);//move cursor line 3
    printf("| %c         |\n",symbol);
    printf ( "\033[4;%dH", col * 14);//move cursor line 4
    printf("|           |\n");
    printf ( "\033[5;%dH", col * 14);//move cursor line 5
    printf("|           |\n");
    printf ( "\033[6;%dH", col * 14);//move cursor line 6
    printf("|           |\n");
    printf ( "\033[7;%dH", col * 14);//move cursor line 7
    printf("|         %c |\n",symbol);
    printf ( "\033[8;%dH", col * 14);//move cursor line 8
    printf("|         %c |\n",name);
    printf ( "\033[9;%dH", col * 14);//move cursor line 9
    printf("-------------\n");
}

答案 1 :(得分:0)

这是对我有用的功能。

void gotoXY(int x, int y)
{

 COORD coord;

 coord.X = x;

 coord.Y = y;

 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

}

感谢@PCLuddite指点我检查setConsoleCursorPosition,这有助于我在线找到上述功能。希望这有助于其他人。