strtol() function in C++

In this guide, you will learn what is strtol() function is in C++ programming and how to use it with an example.

1. strtol() Function Overview

The strtol() function, available in the C++ <cstdlib> standard library, is utilized to convert a C-style string into a long int value. This function parses the content of the given string until it hits an invalid character or the end of the string, returning the long integer representation of the parsed string. It also offers a mechanism to identify invalid characters in the string.

Signature:

long int strtol(const char* str, char** endptr, int base);

Parameters:

- str: A pointer to the null-terminated string that needs to be converted.

- endptr: A pointer to a char* that will be set to point at the first invalid character encountered, or NULL if the entire string was successfully parsed.

- base: The base of the given numeric string. It can range from 2 (binary) to 36. A value of 0 means the function should auto-detect the base (0x for hex, 0 for octal, or decimal otherwise).

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    const char* numStr1 = "0x1a3f extra";
    const char* numStr2 = "07452 more chars";
    char* endPtr;

    long int num1 = strtol(numStr1, &endPtr, 0);
    long int num2 = strtol(numStr2, &endPtr, 0);

    std::cout << "String: " << numStr1 << " as Long Int: " << num1 << std::endl;
    std::cout << "End at: " << endPtr << std::endl;

    std::cout << "String: " << numStr2 << " as Long Int: " << num2 << std::endl;
    std::cout << "End at: " << endPtr << std::endl;

    return 0;
}

Output:

String: 0x1a3f extra as Long Int: 6719
End at: extra
String: 07452 more chars as Long Int: 3914
End at: more chars

3. Explanation

1. Two strings numStr1 and numStr2 are given, containing hexadecimal and octal representations of numbers, followed by extra characters.

2. The strtol() function is invoked with each string, with endPtr address as the second argument and a base of 0 as the third argument, instructing the function to deduce the base from the string itself.

3. The function converts the valid parts of the string to a long int, setting endPtr to the first invalid character encountered.

4. The results show both the converted numbers and the text pointed to by endPtr, showing where the conversion halted.

5. This method is particularly advantageous when requiring detection of errors or when more nuanced parsing is needed. If the string's initial segment isn't a valid number, the function returns 0, and endPtr is directed to the original str.


Comments