在 C 中使用 printf 生成彩色文本

发布于 2024-12-25 09:18:17 字数 92 浏览 3 评论 0原文

我想知道如何在控制台中打印彩色文本?我使用eclipse win64操作系统。谁能用 C 语言给出一个简单的例子,其中只有红色的 hello world 文本或其他文本?

I was wondering how can I print colorful text in the console? I use eclipse win64 OS. Can anyone give a simple example in C with just a hello world text in red or whatever?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

皇甫轩 2025-01-01 09:18:17

我知道这在 C++ 中非常容易做到,但我发现了这个供您在 C 中查看:

#include <stdio.h>
#include <windows.h>   // WinApi header

int main()
{
  HANDLE  hConsole;
    int k;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

  // you can loop k higher to see more color choices
  for(k = 1; k < 255; k++)
  {
    SetConsoleTextAttribute(hConsole, k);
    printf("%3d  %s\n", k, "I want to be nice today!");
  }

  getchar();  // wait
  return 0;
}

所有注释将帮助您找到代码中的方法 - 希望它有所帮助!

I know that this is incredibly easy to do in C++, but I found this for you to look at in C:

#include <stdio.h>
#include <windows.h>   // WinApi header

int main()
{
  HANDLE  hConsole;
    int k;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

  // you can loop k higher to see more color choices
  for(k = 1; k < 255; k++)
  {
    SetConsoleTextAttribute(hConsole, k);
    printf("%3d  %s\n", k, "I want to be nice today!");
  }

  getchar();  // wait
  return 0;
}

All of the comments will help you to find your way through the code - hope it helps!

孤芳又自赏 2025-01-01 09:18:17

如果您想在 Windows 控制台中打印彩色文本,则必须使用 Windows API。 Windows 中不再支持 ANSI.sys。

在 Linux 中,您仍然可以使用 ANSI 转义序列为文本着色。

If you want to print colored text in Windows console, you will have to use Windows API. ANSI.sys support is no longer present in Windows.

In Linux you can still use ANSI escape sequences to color text.

两仪 2025-01-01 09:18:17

您也可以在 Windows 上使用 ANSI 转义序列,并进行以下修改:

reg add HKEY_CURRENT_USER\Console /v VirtualTerminalLevel /t REG_DWORD /d 0x00000001 /f

示例:

int main() 
{
   printf("\033[33mThis is yellow\033[0m");
   return 0;
}

source:
https://www.codeproject.com/Tips /5255355/如何在 Windows 控制台上添加颜色

You can use ANSI escape sequence on Windows as well with the following modification:

reg add HKEY_CURRENT_USER\Console /v VirtualTerminalLevel /t REG_DWORD /d 0x00000001 /f

example:

int main() 
{
   printf("\033[33mThis is yellow\033[0m");
   return 0;
}

source:
https://www.codeproject.com/Tips/5255355/How-to-Put-Color-on-Windows-Console

往事风中埋 2025-01-01 09:18:17

如果您仅限于使用 printf(),则需要了解您正在写入的终端。很可能它是 ANSI 风格的终端,所以可以做到。 Unix curses (Linux ncurses) 库以独立于终端的方式处理此类信息。基本上,您需要定义或制造控制字符串以将终端转变为红色模式,然后再次将其重置回来(但是您如何知道在将其更改为写入红色文本之前它处于什么状态?)。提到的图书馆跟踪状态信息以及许多其他细节。

然而,如果你把字符串组织起来,那么像这样的代码就会达到目的(或多或少):

static const char to_red[] = "\033...";
static const char to_black[] = "\033...";

printf("%s%s%s\n", to_red, "hello world", to_black);

困难的部分是确定常量字符串中的内容(实际上不需要是常量)。

所有这些意味着可能有一个特定于 Windows 的接口可用于完成这项工作,但这并不真正涉及 printf() 来控制颜色;您调用 Windows API 来设置颜色,然后使用 printf() 编写,然后再次调用 API 来恢复颜色。可能有一个查询功能可以让您找到当前设置,您可以在更改之前使用该设置。

If you are constrained to using just printf(), this requires knowledge of the terminal to which you're writing. The chances are it is an ANSI-style terminal, so it can be done. The Unix curses (Linux ncurses) library handles such information in a terminal-independent way. Basically, you will need to define or manufacture control strings to turn the terminal into red mode and then reset it back again (but how do you know what state it was in before you changed it to writing red text?). The libraries mentioned keep track of the state information, amongst many other details.

However, if you get the strings organized, then code like this will do the trick (more or less):

static const char to_red[] = "\033...";
static const char to_black[] = "\033...";

printf("%s%s%s\n", to_red, "hello world", to_black);

The hard part is determining what goes in the constant strings (which need not actually be constant).

All this means there is probably a Windows-specific interface that can be used to do the job, but that does not really involve printf() for controlling the colours; you call the Windows API to set the colour, then write with printf(), then call the API again to reinstate the colour. There is probably a query function to allow you to find the current setting, which you use before changing it.

婴鹅 2025-01-01 09:18:17

Java 中的控制台使用 stdout,它是您运行的任何操作系统。对于 Windows,您需要访问控制台 API 来更改颜色。对于 Linux 或 Mac,控制台可能支持 ANSI 转义序列,它可以通过 stdout 更改控制台颜色。

The console in Java uses stdout which is whatever OS you are running on. For Windows, you would need to access the Console API to change the colours. For Linux or Mac, the console might support ANSI escape sequences which can change the console colours via stdout.

初见你 2025-01-01 09:18:17

这是给您的另一个例子。它是用 C++ 编写的,但我相信你可以处理它;但我在 python 中的示例中也有完全相同的代码。这是我编写的一个小演示,最终用颜色绘制了一些线条。

输入图片此处描述

无论如何,该系列演示位于:

https://github.com/goblinhack/c-plus-plus-python-tutorial

以下示例的完整源代码位于:

https://github.com/goblinhack/c-plus-plus-python-tutorial/blob/master/lesson1/lesson1.cpp

上图的 C++ 代码使用的是 Ansi 颜色类 I在lesson1.cpp中定义。但一旦你使用它,它的使用就非常简单。嗯。

int main (int argc, char *argv[])
{
    Ansi ansi;

    std::cout << ansi.get_code(ansi.FOREGROUND_RED);
    std::cout << "hello ";

    std::cout << ansi.get_code(ansi.FOREGROUND_GREEN);
    std::cout << "beautiful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_CYAN);
    std::cout << " colorful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_BLUE);
    std::cout << " world";
    std::cout << ansi.get_code(ansi.RESET);
    std::cout << std::endl;

    return (0);
}

在Python中具有类似的能力

 def lesson1():
        """ hello beautiful world """
        ansi = Ansi()

        for bg_col in range(ansi.Code.BACKGROUND_BLACK,
                            ansi.Code.BACKGROUND_WHITE):
            for fg_col in range(ansi.Code.FOREGROUND_BLACK,
                                ansi.Code.FOREGROUND_WHITE):
                sys.stdout.write("{0: <20} {1: <20}".format(\
                                 ansi.get_code_name(bg_col),
                                 ansi.get_code_name(fg_col)))
                sys.stdout.write(ansi.get_bgfg_code(bg_col, fg_col))
                sys.stdout.write("colorful")
                sys.stdout.write(ansi.get_code(ansi.Code.RESET))
                print()

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_RED))
        sys.stdout.write("hello")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_GREEN))
        sys.stdout.write(" beautiful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_CYAN))
        sys.stdout.write(" colorful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_BLUE))
        sys.stdout.write(" world")

        sys.stdout.write(ansi.get_code(ansi.Code.RESET))
        print("from Python")

    lesson1()

Here's a further example for you. It is in C++, but I'm sure you can handle that; but I do also have the exact same code in this example in python. It's a small demo I wrote to end up drawing some lines in colors.

enter image description here

Anyway the series of demos is at:

https://github.com/goblinhack/c-plus-plus-python-tutorial

With the full source for the below example at:

https://github.com/goblinhack/c-plus-plus-python-tutorial/blob/master/lesson1/lesson1.cpp

The C++ code for the above picture is using the Ansi color class I define in the lesson1.cpp. But once you use that, it's very simple to use. hth.

int main (int argc, char *argv[])
{
    Ansi ansi;

    std::cout << ansi.get_code(ansi.FOREGROUND_RED);
    std::cout << "hello ";

    std::cout << ansi.get_code(ansi.FOREGROUND_GREEN);
    std::cout << "beautiful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_CYAN);
    std::cout << " colorful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_BLUE);
    std::cout << " world";
    std::cout << ansi.get_code(ansi.RESET);
    std::cout << std::endl;

    return (0);
}

With similar ability in python

 def lesson1():
        """ hello beautiful world """
        ansi = Ansi()

        for bg_col in range(ansi.Code.BACKGROUND_BLACK,
                            ansi.Code.BACKGROUND_WHITE):
            for fg_col in range(ansi.Code.FOREGROUND_BLACK,
                                ansi.Code.FOREGROUND_WHITE):
                sys.stdout.write("{0: <20} {1: <20}".format(\
                                 ansi.get_code_name(bg_col),
                                 ansi.get_code_name(fg_col)))
                sys.stdout.write(ansi.get_bgfg_code(bg_col, fg_col))
                sys.stdout.write("colorful")
                sys.stdout.write(ansi.get_code(ansi.Code.RESET))
                print()

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_RED))
        sys.stdout.write("hello")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_GREEN))
        sys.stdout.write(" beautiful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_CYAN))
        sys.stdout.write(" colorful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_BLUE))
        sys.stdout.write(" world")

        sys.stdout.write(ansi.get_code(ansi.Code.RESET))
        print("from Python")

    lesson1()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文