Stdstol Function In C++ - C++ Programming Tutorial
C++ Course / Functions / Stdstol Function In C++

Stdstol Function In C++

BLUF: Mastering Stdstol Function In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Stdstol Function In C++

C++ is renowned for its efficiency. Learn how Stdstol Function In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, you will be introduced to the std::stol function in C++ along with its syntax and sample illustrations.

What is std::stol?

The C++ Standard Template Library (STL) provides the std::stol function, designed for the purpose of converting strings to long integers. This function proves to be particularly valuable in scenarios involving user input or data retrieval from external origins, where the data is typically presented in string form. Upon receiving a string as input, std::stol processes it and returns the corresponding long integer. In cases where the conversion is not feasible or the input string includes non-numeric characters, an exception of either std::invalidargument or std::outof_range type is raised.

Syntax:

It has the following syntax:

The function std::stol converts a std::string to a long integer value in C++. It accepts an optional parameter for the starting position pos in the string to begin the conversion, and another optional parameter base which specifies the numerical base for the conversion (default is base 10).

The string that requires conversion to a large whole number.

The position of the initial unconverted character in the string is saved as a reference to a size_t object. If it is not needed, this additional parameter can be assigned a value of nullptr.

The numerical base of the conversion is set to ten by default.

The function returns a long integer representing the numeric value extracted from the input string.

Exceptions: In cases where the conversion process fails or when the input string contains invalid characters, the function will raise an exception. If no conversion is successful, the potential exceptions that may occur include std::invalidargument and std::outof_range, particularly when the converted value exceeds the permissible range for a long data type.

Use Cases:

  • Input Processing by Users:

std::stol is a handy function for converting string representations of numerical data, often provided by users, into numeric values that can be utilized for additional processing tasks.

  • Input/Output File:

Reading numeric information from files that contain strings representing the data.

  • Data verification:

Data validation is the process of ensuring that user inputs correctly represent large numerical values through validation and verification.

Example Program 1:

Let's consider an instance to demonstrate the implementation of the std::stol function in the C++ programming language.

Example

#include <iostream>
#include <string>
int main() {
 std::string numStr = "12345";
 try {
 long result = std::stol(numStr);
 std::cout << "Converted value: " << result << std::endl;
 } catch (const std::invalid_argument& e) {
 std::cerr << "Invalid argument: " << e.what() << std::endl;
 } catch (const std::out_of_range& e) {
 std::cerr << "Out of range: " << e.what() << std::endl;
 }
 return 0;
}

Output:

Explanation:

  • Intialization: A string variable called numStr is initialized with the value "12345" at the beginning of the programme.
  • Try Block: The code moves into a try block, signalling that it will try to run the statements contained within. Potential exceptions are dealt with here.
  • Conversion Attempt: The program tries to use std::stol to transform the string numStr into a long integer inside the try block.
  • Effective Conversion: The outcome is kept in the variable result if the conversion is successful.
  • Output Converted Value: The successfully converted number is then printed to the standard output by the program.
  • Treating Exceptions: One of the catch blocks handles any exceptions that arise during the conversion.
  • Exception for Catching Invalid Argument: An error message stating that the argument is invalid is printed if the exception is of the type std::invalid_argument.
  • Exception for Catch Out of Range: An error message stating that the conversion result is outside of the valid range is printed if the exception is of the type std::outofrange.
  • Return Policy: The program returns 0 to the operating system, signifying successful execution, and the main function ends.
  • A string variable called numStr is initialized with the value "12345" at the beginning of the programme.
  • The code moves into a try block, signalling that it will try to run the statements contained within. Potential exceptions are dealt with here.
  • The program tries to use std::stol to transform the string numStr into a long integer inside the try block.
  • The outcome is kept in the variable result if the conversion is successful.
  • The successfully converted number is then printed to the standard output by the program.
  • One of the catch blocks handles any exceptions that arise during the conversion.
  • An error message stating that the argument is invalid is printed if the exception is of the type std::invalid_argument.
  • An error message stating that the conversion result is outside of the valid range is printed if the exception is of the type std::outofrange.
  • The program returns 0 to the operating system, signifying successful execution, and the main function ends.

In short, the code attempts to employ the std::stol function within a try block to change the string "12345" into a long integer. The output is displayed if the conversion is successful. It handles exceptions and showcases the appropriate error message if any issues occur (due to an invalid argument or an out-of-range result).

Ultimately, the program concludes by returning 0 to indicate successful execution.

Example Program 2:

Let's consider another instance to demonstrate the utilization of the std::stol function in C++.

Example

#include <iostream>
#include <string>
int main() {
 std::cout << "Enter numeric strings to convert to long integers (type 'exit' to end):\n";
 while (true) {
 std::string userInput;
 std::cout << "Input: ";
 std::cin >> userInput;

 if (userInput == "exit") {
 std::cout << "Exiting program. Goodbye!\n";
 break;
 }
 try {
 long result = std::stol(userInput);
 std::cout << "Converted Value: " << result << std::endl;
 } catch (const std::invalid_argument& e) {
 std::cerr << "Error: Invalid argument in input '" << userInput << "': " << e.what() << std::endl;
 } catch (const std::out_of_range& e) {
 std::cerr << "Error: Out of range for input '" << userInput << "': " << e.what() << std::endl;
 }
 }
 return 0;
}

Output:

Explanation :

  • In this example, the user is prompted to enter string values to be converted.
  • The application will keep accepting user input until the user inputs "exit" using a while loop.
  • Std::cin is used inside the loop to read user input.
  • Entering "exit" causes this program to print a farewell message and end the loop.
  • If not, it tries to use std::stol to convert the input to a long.
  • The converted value is printed if the conversion is successful.
  • It catches exceptions (invalid arguments, out of range), prints an error message, and continues.
  • As it waits for new user input, the loop moves on to the next iteration.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience