SoFunction
Updated on 2025-04-21

In-depth analysis of the std::stoul function in C++

std::stoul(String to Unsigned Long) is a string conversion function in the C++ standard library, which is used to convertstd::stringorstd::wstringConvert tounsigned longInteger of type and supports conversion of different digits (such as binary, decimal, hexadecimal, etc.).

1. Basic introduction to std::stoul

std::stoulDefined in<string>in the header file and located instdUnder namespace. Its main function is to convert strings tounsigned longInteger of type and supports conversion of different digits

1.1 Function prototype of std::stoul

unsigned long stoul(const std::string& str, size_t* pos = nullptr, int base = 10);
unsigned long stoul(const std::wstring& str, size_t* pos = nullptr, int base = 10);

1.2 Parameter analysis

  • str: The string to be converted must be in a valid unsigned integer format.
  • pos(Optional): If providedposstoulWill be here*posStorages the position where the conversion ends (i.e. the next position of the last converted character).
  • base(Optional): represents the binary system used by the string, the default value is10(decimal), supported2arrive36Binary.

1.3 Return value

  • success: Return to the convertedunsigned longType integer.
  • fail: If the string is not a valid number or exceedsunsigned longThe range of type will throw an exception.

2. The implementation principle of std::stoul

In the GCC standard library<string>In the header file,std::stoulThe underlying implementation is based onstd::strtoul,as follows:

inline unsigned long
stoul(const string&amp; __str, size_t* __idx = 0, int __base = 10)
{
    return __gnu_cxx::__stoa(&amp;std::strtoul, "stoul", __str.c_str(),
                             __idx, __base);
}

2.1 parse implementation code

  • Callstd::strtoulstd::strtoul(String to Unsigned Long) is a standard library function in C language, which can convert C-style strings intounsigned longInteger of type, and also supports binary conversion.
  • use__gnu_cxx::__stoaContain packaging__stoais a tool function in the GNU C++ extension library that is used to convertunsigned longConvert tounsigned long, and perform error checks.
  • __str.c_str()std::stringof.c_str()Method returns oneconst char*,Willstd::stringConvert to C-style strings so thatstd::strtoulAnalysis.

3. The actual usage of std::stoul

3.1 Basic examples

#include &lt;iostream&gt;
#include &lt;string&gt;

int main() {
    std::string str = "123456789";
    unsigned long num = std::stoul(str);  // Default decimal    std::cout &lt;&lt; "Conversion result: " &lt;&lt; num &lt;&lt; std::endl;
    return 0;
}

Output:

Conversion result: 123456789

3.2 Use pos parameter to record the end of the conversion

#include &lt;iostream&gt;
#include &lt;string&gt;

int main() {
    std::string str = "12345xyz";
    std::size_t pos;
    unsigned long num = std::stoul(str, &amp;pos);
    
    std::cout &lt;&lt; "Conversion result: " &lt;&lt; num &lt;&lt; std::endl;
    std::cout &lt;&lt; "Conversion end position: " &lt;&lt; pos &lt;&lt; std::endl;
    
    return 0;
}

Output:

Conversion result: 12345
Conversion end position: 5

Analysis:

  • stoulAnalysis"12345"Later encountered"xyz", stop the conversion, andposSet as5

3.3 Handling conversions of different digits

#include &lt;iostream&gt;
#include &lt;string&gt;

int main() {
    std::string str = "1A";  // Hexadecimal    unsigned long num = std::stoul(str, nullptr, 16);  // parse in hexadecimal    std::cout &lt;&lt; "Conversion result: " &lt;&lt; num &lt;&lt; std::endl;
    
    return 0;
}

Output:

Conversion result: 26

Analysis:

  • 1AIn hexadecimal, equal to26,sostoulreturn26

Other Category Examples

std::stoul("1010", nullptr, 2);  // parse in binary and return 10std::stoul("75", nullptr, 8);    // parse in octal, return 61std::stoul("1F", nullptr, 16);   // parse in hexadecimal, return 31

4. Handle exceptions

4.1 The input is not a valid number

ifstrNot a valid integer format.std::stoulWill be thrownstd::invalid_argumentException:

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;stdexcept&gt;

int main() {
    try {
        std::string str = "abc";  
        unsigned long num = std::stoul(str);
        std::cout &lt;&lt; "Conversion result: " &lt;&lt; num &lt;&lt; std::endl;
    } catch (const std::invalid_argument&amp; e) {
        std::cerr &lt;&lt; "Error: Invalid numeric string -> " &lt;&lt; () &lt;&lt; std::endl;
    }

    return 0;
}

Output:

Error: Invalid numeric string -> stoul

4.2 The value exceeds the unsigned long range

If the value represented by the string exceedsunsigned longThe scope ofstd::stoulWill be thrownstd::out_of_rangeException:

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;climits&gt;

int main() {
    try {
        std::string str = "99999999999999999999";  
        unsigned long num = std::stoul(str);
        std::cout &lt;&lt; "Conversion result: " &lt;&lt; num &lt;&lt; std::endl;
    } catch (const std::out_of_range&amp; e) {
        std::cerr &lt;&lt; "Error: Values ​​out of range -> " &lt;&lt; () &lt;&lt; std::endl;
    }

    return 0;
}

Output:

Error: Values ​​are out of range -> stoul

5. std::stoul related functions

function effect Return type
std::stoi Convert toint int
std::stol Convert tolong long
std::stoll Convert tolong long long long
std::stoul Convert tounsigned long unsigned long
std::stoull Convert tounsigned long long unsigned long long

6. Conclusion

  • std::stoulyesstd::strtoulencapsulation, supports binary conversion.
  • supplyposParameter record conversion position.
  • Possible to throwstd::invalid_argumentandstd::out_of_rangeException.
  • Suitable for converting unsigned integers, such asunsigned long, if the value is larger, you can usestd::stoull

This is the article about in-depth analysis of the std::stoul function in C++. For more related C++ std::stoul content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!