将字符串转换为整数类型T,检查是否存在溢出
Convert string to integer type T, checking for overflow
目标是一个函数,给定一个包含数字的字符串和一个整数类型T
,如果该值适合该类型而没有溢出,则返回成功+转换值,否则返回失败。
使用std::istringstream
从字符串中读取数字适用于某些情况:
template<typename T>
std::pair<bool, T> decode(std::string s)
{
T value;
std::istringstream iss(s);
iss >> std::dec >> value;
return std::pair<bool, T>(!iss.fail(), value);
}
template<typename T>
void testDecode(std::string s)
{
std::pair<bool, T> result = decode<T>(s);
if (result.first)
std::cout << +result.second;
else
std::cout << "ERROR";
std::cout << std::endl;
}
int main()
{
testDecode<int32_t>("12"); // 12
testDecode<int16_t>("1000000"); // ERROR
testDecode<int16_t>("65535"); // ERROR
return 0;
}
然而,对于8位类型(因为这些类型被视为字符(,它失败了:
testDecode<uint8_t>("12"); // 49 !
负数也被错误地接受,并被解析为无符号类型:
testDecode<uint16_t>("-42"); // 65494 !
这样的功能由例如D中的std.conv.to
和Rust中的str::parse
提供。C++的等价物是什么?
您的解决方案看起来不错。然而,如果您想要更好的编译时优化,您应该考虑进行模板专业化。在给出的代码中,您根据类型进行分支。然而,这可能会被编译到代码中,而不是在编译时解决(在已经可能的情况下(。此外,如果您想根据类型添加额外的检查,函数很快就会变得混乱。
我写了我自己版本的转换代码,除了你的代码外,它还检查是否为整数类型提供了科学符号:
#include <type_traits>
#include <utility>
#include <string>
#include <limits>
#include <algorithm>
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<std::is_floating_point<T>::value, std::pair<bool, T>>
{
return std::pair<bool, T>{true, T(std::stold(s))}; //read the string into the biggest floating point possible, and do a narrowing conversion
}
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_signed<T>::value, std::pair<bool, T>>
{
return ((long long)(std::numeric_limits<T>::min()) <= std::stoll(s) && //does the integer in the string fit into the types data range?
std::stoll(s) <= (long long)(std::numeric_limits<T>::max()))
? std::pair<bool, T>{true, T(std::stoll(s))}
: std::pair<bool, T>{false, 0}; //if yes, read the string into the biggest possible integer, and do a narrowing conversion
}
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_unsigned<T>::value, std::pair<bool, T>>
{
return ((unsigned long long)(std::numeric_limits<T>::min()) <= std::stoull(s) && //does the integer in the string fit into the types data range?
std::stoull(s) <= (unsigned long long)(std::numeric_limits<T>::max()))
? std::pair<bool, T>{true, T(std::stoull(s))}
: std::pair<bool, T>{false, 0}; //if yes, read the string into the biggest possible integer, and do a narrowing conversion
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<std::is_floating_point<T>::value, std::pair<bool, T>>
{
return s.empty() ? //is the string empty?
std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to a floating point number
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_signed<T>::value, std::pair<bool, T>>
{
return (s.empty() || //is the string empty?
std::find(std::begin(s), std::end(s), '.') != std::end(s) || //or does it not fit the integer format?
std::find(std::begin(s), std::end(s), ',') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'e') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'E') != std::end(s))
? std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to a signed integer value
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_unsigned<T>::value, std::pair<bool, T>>
{
return (s.empty() || //is the string empty?
std::find(std::begin(s), std::end(s), '.') != std::end(s) || //or does it not fit the integer format?
std::find(std::begin(s), std::end(s), ',') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'e') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'E') != std::end(s) ||
std::find(std::begin(s), std::end(s), '-') != std::end(s))
? //or does it have a sign?
std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to an unsigned integer value
}
这仍然需要在平台之间进行某种程度的移植,因为std::stold
、std::stoll
或std::stoull
可能不可用。但除此之外,它应该独立于平台类型的实现。
编辑:
我忘记了decode
不应该读取数字,而是返回0
的情况。现在已修复。
以下是使用istringstream
并解决其注意事项的直接方法:
template<typename T>
std::pair<bool, T> decode(std::string s)
{
typedef std::pair<bool, T> Result;
if (s.empty())
return Result(false, 0);
if (!std::numeric_limits<T>::is_signed && s[0] == '-')
return Result(false, 0);
if (sizeof(T) == 1)
{
// Special case for char
std::pair<bool, short> result = decode<short>(s);
if (!result.first)
return Result(false, 0);
if (!inrange(result.second, std::numeric_limits<T>::min(), std::numeric_limits<T>::max()))
return Result(false, 0);
return Result(true, (T)result.second);
}
else
{
T value;
std::istringstream iss(s);
iss >> std::dec >> value;
return Result(!iss.fail(), value);
}
}
相关文章:
- 检查是否以特定精度给出双精度
- 地图计数确实很重要,或者只是检查是否存在
- 检查是否安装了 windows10 C++
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- MPI:检查是否有任何进程已终止
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- Vulkan 的传输队列系列功能和显卡支持:条件检查是否准确?
- 如何检查是否定义了固定宽度的整数
- 使用预处理指令检查是否包含标头?
- 在预处理器中检查 g++ 是否使用 -fopenmp 调用
- 将字符串转换为整数类型T,检查是否存在溢出
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 检查是否至少设置了一点而不跳跃
- 在if条件下,右或左改变值的相等性检查是否有任何区别
- C++ 检查是否按下了键,而不是按住了
- 如何在 c++ 中解析包含整数的字符串并检查是否大于最大值
- 检查是否为质数大o
- 检查是否需要 utf8 转换并转换为 utf8
- 如何正确检查 c++ 是否存在注册表项?