SetColor Function

Hello guys,

i use this function
1
2
3
4
5
  string SetColor(unsigned short color){
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon, color);
    return "";
}


to use color for my text. The only problem is that i have to write this before the code for example

1
2
3
4
SetColor(1);
cout << "Hello";
SetColor(32);
cout << " World!" << endl;


Is there anyway so i can use it like this?

 
cout << SetColor(1) << "Hello" << SetColor(32) << " World" << endl;


Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <windows.h>

struct SetColor {
    int n;
    SetColor(int n) : n(n) {}
};

std::ostream& operator<<(std::ostream& os, const SetColor& sc) {
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), sc.n);
    return os;
}

int main() {
    std::cout << SetColor(1) << "Hello" << SetColor(32) << " World\n";
}

Last edited on
How do iomanip' manipulators achieve this? Do they use structures?
I found this: std::ostream& IDENTIFIER(std::ostream &out) { /*code*/ return out;}
But that takes no arguments..

edit:
thaz cool dutch
Last edited on
@dutch

thank you man, it was was not exactly working hat to edit something but now it works with your code! Gj and thank you! SOLVED
@Grime, There is a standard overload of operator<< for such a function (one taking and returning an ostream&).

1
2
3
4
5
6
7
8
9
#include <iostream>

std::ostream& Hello(std::ostream& os) {
    return os << "HELLO";
}

int main() {
    std::cout << Hello << '\n';
}

@Chris26, was your edit changing int to HANDLE? (I had an int there for testing since I don't have Windows.)
Thanks dutch. Makes sense now!
By the way the error was that const HANDLE type can't have an in class initializer. Why tho.

I guess he put the entire statement under the operator<< overload.
@Grime, I should've realized that. The function would need to be constexpr. I've edited the code above. Hopefully it works now. It's not perfect since it's accepting any ostream& but the ostream& needs to be a console.
Topic archived. No new replies allowed.