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

标签 c++ string strtoull

我想确定(在 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/

相关文章:

string - 如何使用 Perl 根据条件修改字符串的最后两个字符

java - 无法将 xml 字符串转换为 w3c 文档

c# - 如何获取简单字符串变量的最后一行 - C#

c、strtoul() 在发生错误/溢出时返回无效值

C++ 在键为自定义类的映射中使用 std::find

c++ - basic_string 等价物的单元测试

php - 如何捕获 Windows cmd shell 的输出?

javascript - 如何在 JavaScript 和 Native Client 模块之间进行通信