【问题标题】:C++ Converting color value String to intC ++将颜色值字符串转换为int
【发布时间】:2013-03-21 22:03:21
【问题描述】:

我尝试通过读取文件来转换颜色代码,检索颜色代码并将其存储为字符串。这行得通,但是当我尝试将其简单地转换为 int 时,它不起作用 - 当我执行 cout 时总是得到 0。

string value = "0xFFFFFF";
unsigned int colorValue = atoi(value.c_str());
cout << colorValue << endl;

如您所见,我得到的颜色是 0xFFFFFF,但将其转换为 int 只会给我 0。有人可以告诉我我缺少什么或我做错了什么吗?

谢谢

【问题讨论】:

  • atoi 是 C 而不是 C++ 方式。我也相信atoi 不能处理十六进制变量。
  • 感谢您的信息,那我必须做什么?
  • @Danny 点击丹尼尔的链接。
  • @DrewDormann 抱歉,在我注意到 Daniel 发表评论之前我已经发表了评论

标签: c++ colors int


【解决方案1】:

我建议使用字符串流:

std::string value = "0xFFFFFF";
unsigned int colorValue;
std::stringstream sstream;
sstream << std::hex << value;
sstream >> colorValue;
cout << colorValue << endl;

【讨论】:

    【解决方案2】:

    正如@BartekBanachewicz 所说,atoi() 不是 C++ 这样做的方式。利用 C++ 流的强大功能并使用 std::istringstream 为您完成。见this

    摘录:

    template <typename DataType>
    DataType convertFromString(std::string MyString)
    {
        DataType retValue;
        std::stringstream stream;
        stream << std::hex << MyString; // Credit to @elusive :)
        stream >> retValue;
        return retValue;
    }
    

    【讨论】:

    • 这是个好主意,但是编写的代码仍然会产生同样的问题。 "0xFFFFFF" 将返回 0
    • 是的,刚刚意识到这一点。解决方案很简单,使用@elusive 的策略。我会更新我的答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2011-05-29
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多