std::stol function in C++In this article, you will learn about the std::stol function in C++ with its syntax and examples. What is std::stol()?The Standard Template Library (STL) in C++ includes the std::stol() function, which is specifically made for converting strings to long integers. This function is especially helpful when working with user input or reading data from external sources-where the input is usually given in string format. It returns the equivalent long integer after receiving a string as input. An exception of type std::invalid_argument or std::out_of_range is thrown if the conversion is not possible or if the input string contains characters that are not part of a valid number. Syntax:It has the following syntax: long std::stol(const std::string& str, size_t* pos = 0, int base = 10); str: The text that needs to be changed into a long integer. Pos: The index of the string's first unconverted character, stored as a pointer to a size_t object. If it is not required, this optional parameter can be set to nullptr. base: The conversion's numerical base. Ten is the default. Return Value: The numeric value that was parsed from the input string is returned by the function as a long integer. Exceptions: The function throws an exception if the conversion cannot be completed or if characters in the input string are invalid. If no conversion could be done, the possible exceptions are std::invalid_argument and std::out_of_range if the converted value is greater than the representable range for a long. Use Cases:
std::stol() is useful for transforming numerical input that is received from users in string format into a numeric type so that it may be processed further.
Reading numerical data in files containing strings as the data's representation.
Data validation involves confirming that user inputs accurately represent long numbers by validating and verifying them. Example Program 1:Let's take an example to illustrate the use of std::stol function in C++. Output: Explanation:
In brief, the code tries to use the std::stol() function inside of a try block to convert the string "12345" to a long integer. The result is printed if the conversion is successful. It captures exceptions and prints the relevant error message in the event that one arises (either because of an incorrect argument or because the result is outside of range). Finally, the program returns 0, signifying successful completion. Example Program 2:Let's take another example to illustrate the use of std::stol function in C++. Output: Explanation :
Next Topicstd::stoll() Function in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India