字符串看起来像“#123456”,结果应该是:
int r = 0x12;
int g = 0x34;
int b = 0x56;
或者在 c++ 中简单地反转此任务:
How to convert RGB int values to string color
我知道我可以将当前字符串拆分为 3 个子字符串,但如何将它们实现为十六进制值?
最佳答案
使用标准库的std::hex
:
#include <iostream>
#include <sstream>
int main()
{
// The hex code that should be converted ...
std::string hexCode;
std::cout << "Please enter the hex code: ";
std::cin >> hexCode;
// ... and the target rgb integer values.
int r, g, b;
// Remove the hashtag ...
if(hexCode.at(0) == '#') {
hexCode = hexCode.erase(0, 1);
}
// ... and extract the rgb values.
std::istringstream(hexCode.substr(0,2)) >> std::hex >> r;
std::istringstream(hexCode.substr(2,2)) >> std::hex >> g;
std::istringstream(hexCode.substr(4,2)) >> std::hex >> b;
// Finally dump the result.
std::cout << std::dec << "Parsing #" << hexCode
<< " as hex gives (" << r << ", " << g << ", " << b << ")" << '\n';
}
关于C++,STL。将带有 rgb 颜色的字符串转换为 3 个 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398468/