c++ - 从 std::string 转换为 uint8

标签 c++ stdstring

引用这里提供的漂亮解决方案, Convert string to int with bool/fail in C++ ,

我想将 std::string 转换为 8 位数字(无符号或有符号) 问题是因为 8 位数字被表示为一个字符所以它被解析错误
(尝试解析超过 1 位数字的任何内容 - 例如 10 - 失败)

有什么想法吗?

最佳答案

使用模板特化:

template <typename T>
void Convert(const std::string& source, T& target)
{
    target = boost::lexical_cast<T>(source);
}

template <>
void Convert(const std::string& source, int8_t& target)
{
    int value = boost::lexical_cast<int>(source);

    if(value < std::numeric_limits<int8_t>::min() || value > std::numeric_limits<int8_t>::max())
    {
        //handle error
    }
    else
    {
        target = (int8_t)value;
    }
}

关于c++ - 从 std::string 转换为 uint8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601919/

相关文章:

c++ - std::string::assign() 导致段错误

c++ - 为什么 6-7 个线程比 20 个线程快?

c++ - 如何在同一解决方案下为多个项目声明公共(public)#define?

C++ 错误 : Type Name is Not Allowed

c++ - 初始化并使用 C++ std::string 作为 char 数组

c++ - 如何检查字符串是否包含字符?

c++ - 需要 PRBS 模式生成 C/C++ API

c++ - 使用 stringstream 格式化日期

带有 u8、char8_t 和 std::string 的 C++20

c++ - std::string 是否不如 QString?