String to int Conversion Using strtol()
Using the strtol functions: It converts a string to a long integer value, respectively.
Syntax of strtol():
long int strtol(const char* str, char** endptr, int base);
Parameters:
- str- Pointer to the null-terminated byte string to be converted
- endptr- Reference to a pointer to character. The function stores the address of the first invalid character in *endptr. If endptr is a null pointer, the function does not store this information.
- base- The number base to interpret the string. Must be between 2 and 36, inclusive, or 0. If base is 0, the function determines the base from the string itself. If the base is 16, the string may begin with the prefix “0x” or “0X”, in which case the number is parsed as a hexadecimal value.
Return:
- If the string is empty or does not contain any digits, 0 is returned.
- If the conversion is successful, the function returns the converted long integer value.
- If the conversion fails, the function returns 0 and sets *endptr to point to the beginning of the string.
Example:
C++
#include <stdio.h> #include <stdlib.h> int main() { char str[] = "12345" ; char * endptr; long int value = strtol (str, &endptr, 10); if (endptr == str) { printf ( "No digits were found\n" ); } else if (*endptr != '\0' ) { printf ( "Invalid input: %s\n" , str); } else { printf ( "The value is %ld\n" , value); } return 0; } |
Output
The value is 12345
Time Complexity: O(N), where N is the number of characters in the string.
Auxiliary Space: O(1)
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings.
Example:
str=”191″
num=191
There are 5 significant methods to convert strings to numbers in C++ as follows:
- Using stoi() function
- Using atoi() function
- Using stringstream
- Using sscanf() function
- Using for Loop
- Using strtol() function
Contact Us