简体   繁体   English

转义符不起作用

[英]Escape character doesn't work

I want to move the cursor to the x,y position so i use: 我想将光标移动到x,y位置,所以我使用:

#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. 我尝试将\\ e更改为%c,0x1B,作为我朋友的示例文件,但仍然无法正常工作。 It only work in my friend file. 它仅在我的朋友文件中起作用。 What should I do to make it work? 我应该怎么做才能使其正常工作? or Should I use windows.h instead? 还是应该改用windows.h?

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. 代码中的\\e是错误的,但是当您通过转义字符的ASCII代码替换它并将f更改为H以使其成为正确的光标定位顺序时,您的代码将在实现ANSI转义序列的所有终端上工作。 This includes many terminals on Linux and other *nix-like systems. 这包括Linux和其他* nix类系统上的许多终端。

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: Windows控制台还支持从Windows 10开始的ANSI转义序列,但是为了向后兼容,默认情况下cmd.exe禁用了此支持,因此要使此代码在Windows 10上有效,必须显式启用此模式:

#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. 话虽如此,您应该真正考虑使用curses There are two widespread implementations of the curses library, ncurses and pdcurses . curses库有两种广泛的实现, ncursespdcurses Both work on a wide variety of systems. 两者均可在多种系统上工作。 My personal recommendation would be ncurses for *nix systems and pdcurses for windows. 我个人的建议是* nix系统的ncurses和Windows的pdcurses If you just #include <curses.h> in your code, you can link to both libraries as you want. 如果仅在代码中#include <curses.h> ,则可以根据需要链接到两个库。 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). 您将获得对终端/控制台输出的完全控制,而不必依赖于可能无法移植的转义序列(它也将在Windows 10之前的版本上运行)。

For learning how to use curses , consider the NCURSES Programming HOWTO . 要学习如何使用curses ,请考虑《 NCURSES编程指南》

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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