简体   繁体   中英

colored text in windows command prompt in one line

I want to change specific words color in windows command prompt, it work like this just fine:

#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;
}

but I want my function work like this

#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;
}

when I run it only setcolor(13) works and then color never changes till the end , what should I do to fix this problem

My comment may be wrong, it might be possible with an I/O manipulator (like std::setw and family):

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;
    }
};

Use it like before:

std::cout << "Hello " << setcolor(50) << "world\n";

Note: I have no idea if this will work, as I have not tested it.


The problem you have now with your current code (as shown in the question) is that setcolor is a normal function which returns a string, and you just call the functions and print their return value (the empty string).

You need to put the output into a separate function:

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

You can then call

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

Still not a one liner but cleaner than your first option :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM