gpt4 book ai didi

C 中的控制台着色无法正常工作

转载 作者:行者123 更新时间:2023-12-01 23:41:25 24 4
gpt4 key购买 nike

我正在尝试用 C 编写一个简单的应用程序,我对 C 的概念还很陌生,所以如果这很简单,我深表歉意。我正在运行 Windows 7 并且有一些类似的东西:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>

#define Green "\33[0:32m"
#define Yellow "\33[0:33m"
#define Reset "\33[0m"
#define Log_info(X) printf("[Info] %s %s %s\n", Green,X,Reset)
#define Log_warn(X) printf("[Warning] %s %s %s\n",Yellow,X,Reset)
#define Seperator() printf("----------------------------------------------------\n")

void info(const char *message)
{
Log_info(message);
Seperator();
}

void warn(const char *message)
{
Log_warn(message);
Seperator();
}

int main(int argc, char *argv[])
{
warn("test the warning output for the console");
info("test the information output for the console");
}

但是,当我尝试运行信息处理时,我得到以下信息:

[Warning] ←[0:33m test the warning output for the console ←[0m
----------------------------------------------------
[Info] ←[0:32m test the information output for the console ←[0m
----------------------------------------------------

我做错了什么,以至于它不是颜色协调输出,而是使用箭头?如何对信息进行颜色协调,黄色表示警告,绿色表示信息?

我想到了使用 \33[0:32m主要来自 Javascript ( \033[32m #<=Green ) 和 Ruby ( \e[32m #<=Green )。

最佳答案

您没有使用正确的颜色代码。并且这些颜色代码仅适用于具有兼容终端的 Unix 系统。

由于您需要 C 和 Windows 特定的解决方案,我建议使用 Win32 API 中的 SetConsoleTextAttribute() 函数。您需要获取控制台的句柄,然后将其与适当的属性一起传递。

举个简单的例子:

/* Change console text color, then restore it back to normal. */
#include <stdio.h>
#include <windows.h>

int main() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
WORD saved_attributes;

/* Save current attributes */
GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
saved_attributes = consoleInfo.wAttributes;

SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
printf("This is some nice COLORFUL text, isn't it?");

/* Restore original attributes */
SetConsoleTextAttribute(hConsole, saved_attributes);
printf("Back to normal");

return 0;
}

有关可用属性的更多信息,请查看 here .

关于C 中的控制台着色无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com