如何在 c++ 中解析包含整数的字符串并检查是否大于最大值

How to parse a string containing an integer and check if greater than a maximum in c++

本文关键字:串并 字符串 字符 检查 是否 最大值 大于 整数 c++ 包含      更新时间:2023-10-16

我想确定(在 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如果您不想处理异常。

现代方法是使用 std::stoi, std::stoll 等

字符串和字符串有重载,可以处理较大的尺寸。

https://en.cppreference.com/w/cpp/string/basic_string/stol

您可以在循环中逐个字符搜索字符串,每次出现连续数字时,您都可以建立一个整数,同时检查Max UINT。