C++ std::stol() Function

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

Definition

In C++, std::stol() converts a string to 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::stol(...).

Syntax

Same pattern as stoi.

C++
long n = std::stol("1000");
CallWhat it does
std::stol(str)Parse as long (optional idx and base).

Use when values may exceed int but fit in long.

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

Parameters

ParameterDescription
strInput text.
idx, baseOptional end index and numeric base.

Return Value

Return ValueDescription
longParsed value.

C++ Examples

Example 1 — Basic stol()

Convert to long.

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

int main() {
    long n = std::stol("12345");
    std::cout << n << '\\n';
    return 0;
}

How It Works

  1. Digits are parsed as base 10.
  2. Result type is long.
  3. Printed as 12345.

Example 2 — Negative long

Parse a signed value.

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

int main() {
    long n = std::stol("  -99");
    std::cout << n << '\\n';
    return 0;
}

How It Works

  1. Leading spaces are skipped.
  2. Sign and digits are read.
  3. Value is -99.

Example 3 — Hex With stol

Parse hex.

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

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

How It Works

  1. Base 16 interprets "10" as sixteen.
  2. nullptr means we ignore the end index.
  3. Output is 16 in decimal.

Frequently Asked Questions

A long parsed from the string.
Yes—invalid_argument and out_of_range.
When the value may not fit in int.
<string>.
stoul.

Next: stold()

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

stold() 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.

15 people found this page helpful