std :: iStream到未签名的数值,如何检测负值
std::istream to unsigned numerical value, how to detect negative values?
我正在研究模板功能,将字符串转换为一个数字,以编译某些不带C 11的遗留代码。
功能是:
template<typename T>
void checkValid( const std::string& val )
{
std::stringstream str1;
T temp1;
str1 << val;
str1 >> temp1;
if ( str1.fail() || str1.bad() )
std::cout << "error, " << val << " is not a valid string value" << std::endl;
else
std::cout << "ok, " << val << " is converted to " << temp1 << std::endl;
}
它运行良好,除了负值:
// valid integer
checkValid<int>( "3" );
// valid integer
checkValid<int>( "-1000" );
// invalid integer
checkValid<int>( "foo" );
// invalid integer out of range (>INT_MAX)
checkValid<int>( "8393930300303" );
// invalid integer out of range (<INT_MIN)
checkValid<int>( "-8393930300303" );
// valid unsigned integer
checkValid<unsigned int>( "3" );
// invalid unsigned integer
checkValid<unsigned int>( "foo" );
// unsigned integer out of range (>UINT_MAX)
checkValid<unsigned int>( "8393930300303" );
// unsigned integer out of range (<0)
checkValid<unsigned int>( "-3" );
此输出:
ok, 3 is converted to 3
ok, -1000 is converted to -1000
error, foo is not a valid string value
error, 8393930300303 is not a valid string value
error, -8393930300303 is not a valid string value
ok, 3 is converted to 3
error, foo is not a valid string value
error, 8393930300303 is not a valid string value
ok, -3 is converted to 4294967293
我期望的是最后一行:
error, -3 is not a valid string value
当目标类型未符号时,负字符串值未正确处理。修复checkValid
的最佳策略是什么是所有类型(签名的,未签名的数值和浮动/double(的预期的最佳策略?
允许流的无符号类型的负数。它具有与
相同的机制unsigned type foo = -some_value
由于它们可以接受负数,因此流将永远不会失败,您将具有将负数分配给无符号类型的正常行为。
,我们可以在您的功能中添加此检查。对于T
类型,T() - T(1) < 0
,只有在签名类型时才是正确的,否则减法将缠绕并成为最大的值T
代表。因此,如果我们检查该条件,并且字符串以'-'
开头,那么您就会知道它不是"有效"值。这使您的功能看起来像
template<typename T>
void checkValid( const std::string& val )
{
std::stringstream str1;
T temp1;
str1 << val;
str1 >> temp1;
if ( str1.fail() || str1.bad() || (!(T() - T(1) < T()) && val[0] == '-') )
std::cout << "error, " << val << " is not a valid string value" << std::endl;
else
std::cout << "ok, " << val << " is converted to " << temp1 << std::endl;
}
如果您的字符串可以具有领先的空格,则您需要用val[val.find_first_not_of(" ")] == '-'
val[0] == '-'
检查
相关文章:
- 使用CMake检测支持的C++标准
- 当套接字连接断开时检测C/C++Unix
- C/C++预处理器是否可以检测一些编译器选项
- WMI检测进程创建事件-c++
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 下面是我为检测链接列表中的循环而制作的代码
- 落砂模拟碰撞检测C++和SFML
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 为什么C++编译器没有检测到正确声明的类?
- 检测win32服务创建和删除的最佳方法
- 正在LLVM中检测整数比较条件
- 如何在鼠标挂钩过程中检测拖动
- 位移操作和位掩码未检测到重复字符
- 检测 COFF 对象文件中C++内联符号
- qmake:检测目标位宽(32 位或 64 位)
- 增强精神解析器规则以检测语句中的特殊结尾
- 用于C++的静态二进制检测或二进制重写工具和框架
- Tensorflow对象检测在Python和C++(OpenCV)之间有不同的结果
- C++中的张量流对象检测
- 边缘检测-检测错误