Windows 命令提示符中的彩色文本在一行中

colored text in windows command prompt in one line

本文关键字:一行 文本 命令提示符 彩色 Windows      更新时间:2023-10-16

我想在Windows命令提示符下更改特定的单词颜色,它的工作原理很好:

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
string setcolor(unsigned short color){
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon, color);
    return "";
}
int main(int argc, char** argv)
{
    setcolor(13);
    cout << "Hello ";
    setcolor(11);
    cout << "World!" << endl;
    setcolor(7);
    system("PAUSE");
    return 0;
}

但我希望我的函数像这样工作

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
string setcolor(unsigned short color){
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon, color);
    return "";
}
int main(int argc, char** argv)
{
    cout << setcolor(13) << "Hello " << setcolor(50) << "World!" << setcolor(7) << endl;
    system("PAUSE");
    return 0;
}

当我运行它时,只有setcolor(13)工作,然后颜色永远不会改变直到最后,我应该怎么做才能解决这个问题

我的评论可能是错误的,使用 I/O 操纵器(如 std::setw 和家人)可能是可能的:

struct setcolor
{
    int color;
    setcolor(int c) : color(c) {}
    std::ostream& operator()(std::ostream& os)
    {
        HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleTextAttribute(hcon, color);
        return os;
    }
};

像以前一样使用它:

std::cout << "Hello " << setcolor(50) << "worldn";

注意:我不知道这是否有效,因为我还没有测试过它。


您现在使用当前代码(如问题所示)遇到的问题是setcolor是一个返回字符串的普通函数,您只需调用这些函数并打印它们的返回值(空字符串)。

您需要将输出放入一个单独的函数中:

void WriteInColor(unsigned short color, string outputString)
{
   HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
   SetConsoleTextAttribute(hcon, color);
   cout << outputString;
}

然后,您可以致电

int main(int argc, char** argv)
{
   WriteInColor(13, "Hello");
   WriteInColor(50, "World");
   WriteInColor(7, "rn");
}

仍然不是单衬垫,但比您的第一个选择更干净:)