我想确定(在c ++中)字符串是否包含范围为0-UINT_MAX的数字 我已经尝试过atoi等,但是不能处理这种情况。 例如,字符串42949672963将无法通过测试 有人有任何建议吗?
答案 0 :(得分:2)
您可以使用标准的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
。
答案 1 :(得分:1)
现代方法是使用std :: stoi,std :: stoll等
string和wstring有重载,并且可以处理较大的大小。
答案 2 :(得分:1)
您可以在一个循环中逐个字符地搜索字符串,每次连续出现数字时,您都可以建立一个整数,同时使用Max UINT进行检查。