C++,STL。将带有 rgb 颜色的字符串转换为 3 个 int 值?

标签 c++ string stl hex rgb

字符串看起来像“#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/

相关文章:

c++ - 为什么 C++ 删除运算符不将指针设置为 NULL?

c++ - 数据成员线程和互斥体的初始化。错误的顺序是否有未定义的行为?

c++ - 组合位图 - GDI/GDI+?

c++ - 错误 C1083 无法打开包含文件 : 'pybind11/pybind11.h' : No such file or directory

string - 在 Kotlin 中装箱字符串字段或扩展所有字符串的替代方案?

c++ - 关于纯抽象类中的静态成员函数 - 设计模式?

c++ - 将 std::vector 转换为数组

string - 字符串的 pretty-print (确保自动换行符保持在给定的打印边距内)

java - 将字符串分割为前两个空格

C++11 前向声明线程、互斥体、计时