Im trying to take a hex color code and determine which color it is im only doing the five basic colors. This is my code to take rgb and return hex code.
string rgbtohex(int r, int g, int b, bool with_head) //the following turns rgb values to hex values.
{
stringstream ss;
if (with_head)
ss<< "#";
ss<<hex<<(r << 16 | g << 8 | b );
return ss.str();
}
I can output the hex code by using this
cout<<rgbtohex(r,b,g,true)<<endl; //outputs hex color code
I want to make a function that will take the rgbtohex output and return the color. Something like this
string hextocolor()
{
if(rgbtohex(r,g,b,true) = "#ff0000"){
cout<<"Red"<<endl;
}
}
This would work for turning in to hex:
string rgbToHex(uint8_t r, uint8_t g, uint8_t b, bool withHead){
stringstream ss;
if (with_head)
ss<< "#";
ss << hex << r;
ss << hex << g;
ss << hex << b;
return ss.str();
}
I think your original solution also worked, The problem is that you used =
instead of ==
in your if statement in hexToColor
.
With std::map
, you might do something like
std::string toColorName(const std::string& hexColor)
{
static const std::map<std::string, std::string> colors{
{"#000000", "black"},
{"#0000ff", "blue"},
{"#00ff00", "green"},
{"#ff0000", "red"},
{"#ffffff", "white"}
};
return colors.at(hexColor);
}
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.