在 C 中使用 printf 实现彩色文本

问题描述 投票:0回答:6

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

c windows colors printf
6个回答
25
投票

我知道这在 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;
}

所有评论将帮助您找到代码的方法 - 希望它有帮助!


7
投票

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

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


7
投票

您也可以在 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;
}

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


3
投票

如果您只能使用

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

但是,如果你组织好字符串,那么像这样的代码就可以达到目的(或多或少):

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 来恢复颜色。可能有一个查询功能可以让您找到当前设置,您可以在更改之前使用该设置。


0
投票

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


0
投票

这是给您的另一个例子。它是用 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++代码使用了我在lesson1.cpp中定义的Ansi颜色类。但一旦你使用它,它的使用就非常简单。哈。

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()
© www.soinside.com 2019 - 2024. All rights reserved.