我想确定(在 C++ 中)字符串是否包含 0 - UINT_MAX 范围内的数字 我试过 atoi 等,但不处理这种情况。 例如字符串 42949672963 将无法通过测试 有人有什么建议吗?
最佳答案
您可以使用标准 C++ 函数 std::strtoul
然后检查转换后的数字是否不大于std::numeric_limits<unsigned int>::max()
.
例如
#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
int main()
{
std::string s( "42949672963" );
unsigned int n = 0;
try
{
unsigned long tmp = std::stoul( s );
if ( std::numeric_limits<unsigned int>::max() < tmp )
{
throw std::out_of_range( "Too big number!" );
}
n = tmp;
}
catch ( const std::out_of_range &e )
{
std::cout << e.what() << '\n';
}
std::cout << "n = " << n << '\n';
return 0;
}
程序输出为
Too big number!
n = 0
您还可以为无效的数字表示再添加一个陷阱。
另一种方法是使用标准 C 函数 strtoul
如果您不想处理异常。
关于c++ - 如何解析包含整数的字符串并检查是否大于 C++ 中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58319823/