In this guide, you will explore the std::stoll function in C++ along with its syntax and illustrations.
What is std::stoll?
The C++ Standard Template Library (STL) features the std::stoll function, specifically designed for converting strings to long long integers. This function proves to be extremely useful when handling very large numerical values that exceed the capacity of a regular long integer. By employing the std::stoll function, strings can seamlessly be transformed into long long integers, providing a solution for dealing with extensive numeric data that cannot be accommodated by standard long integers. Despite returning a long long integer instead of std::stol, the std::stoll function behaves identically in functionality.
Syntax:
It has the following syntax:
The function std::stoll from the Standard Library is used to convert a std::string into a long long integer. It allows you to specify the base for the conversion and also provides the option to track the position of the first character that couldn't be converted.
The string that needs to be converted to an extended integer.
The position of the initial unconverted character in the string is maintained as a reference to a size_t object. If this information is not needed, the optional argument can be assigned a value of nullptr.
The numerical base of the conversion can be adjusted, with the default value being ten.
Return Value: The function retrieves the numerical value from the provided string and outputs it as a long long integer.
Exception: Similar to std::stol, this function throws exceptions when the conversion is unsuccessful or when there are invalid characters in the input string. It may throw std::invalidargument if the conversion fails, and std::outof_range if the resulting value is too large to be stored.
Use Cases:
- Managing Big Numerical Amounts: When working with big numerical values that might go outside of the representable range of a normal long integer.
- Data Processing: Data processing is helpful when receiving or storing numerical data in string format and needing to be translated before computation can take place.
- Data Validation: Data validation is the process of confirming that input from users or data read from other sources are accurate long long integers.
- When working with big numerical values that might go outside of the representable range of a normal long integer.
- Data processing is helpful when receiving or storing numerical data in string format and needing to be translated before computation can take place.
- Data validation is the process of confirming that input from users or data read from other sources are accurate long long integers.
Example Program 1:
Let's consider an example to demonstrate the utilization of the std::stoll function in the C++ programming language.
#include <iostream>
#include <string>
int main() {
std::string numStr = "9876543210";
try {
long long result = std::stoll(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:
Example Program 2:
Let's consider another instance to demonstrate the utilization of the std::stoll function in the C++ programming language.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
// Open a file containing numeric data in string format
std::ifstream inputFile("numeric_data.txt");
if (!inputFile.is_open()) {
std::cerr << "Error: Unable to open the file." << std::endl;
return 1; // Return with an error code
}
std::vector<std::string> numericStrings;
std::string currentLine;
// Read lines from the file and store them in a vector
while (std::getline(inputFile, currentLine)) {
numericStrings.push_back(currentLine);
}
// Close the file
inputFile.close();
// Process the numeric strings and calculate the sum
long long sum = 0;
for (const auto& numStr : numericStrings) {
try {
long long result = std::stoll(numStr);
sum += result;
} catch (const std::invalid_argument& e) {
std::cerr << "Error: Invalid argument in string '" << numStr << "': " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Error: Out of range for string '" << numStr << "': " << e.what() << std::endl;
}
}
// Output the sum of converted values
std::cout << "Sum of converted values: " << sum << std::endl;
return 0;
}
Output:
Explanation:
- Opening of File: An attempt is made by the program to read a file called "numeric_data.txt" . An error message reflecting the failure is printed to the standard error if the file cannot be opened. After that, the application indicates that there was a problem opening the file by returning an error code of 1.
- Reading Text from the Document: The program to hold strings initializes an empty vector called numericStrings . After that, it starts reading every line from the opened file ( inputFile ) in a loop. It saves the content in the currentLine string for every line. Next, the numericStrings vector is expanded to include the currentLine . Until the file has no more lines, this operation is repeated.
- Closing of File: String the close command, the file is closed once all of its lines have been read.
- Handling Numerical Strings and Finding the Sum: The program initializes a variable called sum to track the total of the converted values. Every string in numericStrings is iterated over. It tries to use std::stoll to turn each string into a long long. The converted value is added to the total if the conversion is successful. It captures the exception, prints an error message, and moves on to the next string in the event of an exception (invalid argument or out of range).
- Producing the Total: After that, the total of the converted values is printed to the standard output by the program.
- An attempt is made by the program to read a file called "numeric_data.txt" .
- An error message reflecting the failure is printed to the standard error if the file cannot be opened.
- After that, the application indicates that there was a problem opening the file by returning an error code of 1.
- The program to hold strings initializes an empty vector called numericStrings .
- After that, it starts reading every line from the opened file ( inputFile ) in a loop.
- It saves the content in the currentLine string for every line.
- Next, the numericStrings vector is expanded to include the currentLine .
- Until the file has no more lines, this operation is repeated.
- String the close command, the file is closed once all of its lines have been read.
- The program initializes a variable called sum to track the total of the converted values.
- Every string in numericStrings is iterated over.
- It tries to use std::stoll to turn each string into a long long.
- The converted value is added to the total if the conversion is successful.
- It captures the exception, prints an error message, and moves on to the next string in the event of an exception (invalid argument or out of range).
- After that, the total of the converted values is printed to the standard output by the program.