简体   繁体   中英

Escape character doesn't work

I want to move the cursor to the x,y position so i use:

#include <stdio.h>

int main()
{

    int x = 10, y = 10   
    printf("\e[%d;%df",y,x);
    printf("HelloWorld");

}

but it's output is:

[10;10fHelloWorld

I try to change from \\e to %c, 0x1B as an example file from my friend but it still not work. It only work in my friend file. What should I do to make it work? or Should I use windows.h instead?

The \\e in your code is wrong, but when you repace it by the ASCII code of an escape character and also change f to H to make it the correct sequence for cursor positioning, your code will work on all terminals that implement ANSI escape sequences. This includes many terminals on Linux and other *nix-like systems.

The windows console also supports ANSI escape sequences starting from Windows 10, but this support is disabled by cmd.exe by default for backwards compatibility, so to make this code work on Windows 10, you have to explicitly enable this mode:

#include <stdio.h>
#include <windows.h>

// this line is only for older versions of windows headers (pre Win 10):
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004

int main(void)
{
    // enable ANSI sequences for windows 10:
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD consoleMode;
    GetConsoleMode(console, &consoleMode);
    consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    SetConsoleMode(console, consoleMode);

    int x = 10, y = 10;
    printf("\x1b[%d;%dH", y, x);
    printf("HelloWorld");
}

But that all said, you should really consider using curses instead. There are two widespread implementations of the curses library, ncurses and pdcurses . Both work on a wide variety of systems. My personal recommendation would be ncurses for *nix systems and pdcurses for windows. If you just #include <curses.h> in your code, you can link to both libraries as you want. What you get is full control of your terminal/console output without relying on possibly non-portable escape sequences (it will work on earlier versions than Windows 10 as well).

For learning how to use curses , consider the NCURSES Programming HOWTO .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM