C++ std::stoul() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::stoul

Definition

In C++, std::stoul() converts a string to unsigned long.

Include <string>.

This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::stoul(...).

Syntax

Pass unsigned-looking text.

C++
unsigned long n = std::stoul("255");
CallWhat it does
std::stoul(str)Parse as unsigned long.

For 64-bit unsigned values prefer stoull when needed.

Library declarations
C++
unsigned long stoul(const string& str, size_t* idx = 0, int base = 10);

Parameters

ParameterDescription
strInput.
idx, baseOptional.

Return Value

Return ValueDescription
unsigned longParsed value.

C++ Examples

Example 1 — Basic stoul()

Convert to unsigned long.

C++
#include <iostream>
#include <string>

int main() {
    unsigned long n = std::stoul("255");
    std::cout << n << '\\n';
    return 0;
}

How It Works

  1. Digits parse as base 10.
  2. Type is unsigned long.
  3. Prints 255.

Example 2 — stoul Hex

Parse hex color-like text.

C++
#include <iostream>
#include <string>

int main() {
    unsigned long n = std::stoul("ff", nullptr, 16);
    std::cout << n << '\\n';
    return 0;
}

How It Works

  1. Base 16 reads ff.
  2. Value is 255.
  3. Shown in decimal.

Example 3 — stoul idx

Stop at non-digit.

C++
#include <iostream>
#include <string>

int main() {
    std::size_t i = 0;
    unsigned long n = std::stoul("10px", &i);
    std::cout << n << ' ' << i << '\\n';
    return 0;
}

How It Works

  1. Parses 10.
  2. Stops at p.
  3. idx is 2.

Frequently Asked Questions

Parses unsigned long from a string.
stol.
stoull.
invalid_argument / out_of_range.
<string>.

Next: stoull()

Keep going through the string functions. Convert a string to unsigned long long.

stoull() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful