1

我想确定(在 C++ 中)一个字符串是否包含一个在 0 - UINT_MAX 范围内的数字我已经尝试过 atoi 等,但不处理这种情况。例如字符串 42949672963 将无法通过测试有没有人有任何建议?

4

3 回答 3

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

您还可以为无效数字表示再添加一个捕获。

strtoul如果您不想处理异常,另一种方法是使用标准 C 函数。

于 2019-10-10T09:50:59.227 回答
1

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

string 和 wstring 有重载,并且可以处理更大的大小。

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

于 2019-10-10T09:41:42.077 回答
1

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

于 2019-10-10T09:49:34.483 回答