How can I print a string to the console at specific coordinates in C++?

后端 未结 7 1251
温柔的废话
温柔的废话 2020-12-01 15:24

I\'m trying to print characters in the console at specified coordinates. Up to now I have been using the very ugly printf(\"\\033[%d;%dH%s\\n\", 2, 2, \"str\");

相关标签:
7条回答
  • 2020-12-01 16:00

    A few improvements to your function:

    void printToCoordinates(int x, int y, const char *format, ...)
    {
        va_list args;
        va_start(args, format);
        printf("\033[%d;%dH", x, y);
        vprintf(format, args);
        va_end(args);
        fflush(stdout);
    }
    

    This version:

    • allows you to use any arbitrary format string and variable argument lists
    • automatically flushes stdout without printing a newline
    • uses x and y in the format string (your use of x and x may have been a typo)

    However, because varargs is essentially a C feature and doesn't really understand C++ objects, you'd have to call it like this:

    printToCoordinates(10, 10, "%s", text.c_str());
    

    A better option really is to use curses (for Unix-like platforms) or Win32 console functions (for Windows) as mentioned in other answers.

    0 讨论(0)
提交回复
热议问题