Converting String to Long in C
Here, we will see how to build a C Program For String to Long Conversion using strtol() function.
Syntax:
long int strtol(char *string, char **ptr, int base)
- The first argument is given as a string
- The second argument is a reference to an object of type char*
- The third argument denotes the base in which the number is represented. To know more about visit strtol() function.
Note: We don’t have to use long int in the case of strtoul() because the range of unsigned long is greater than long on the positive front.
[long : -2147483648 to 2147483647 and unsigned long : 0 to 4294967295]Syntax:
strtoul(char *string, char **ptr, int base) // no long int need in strtoul()
C
// C program to demonstrate working of strol() #include <stdio.h> #include <stdlib.h> int main() { // To store Number in String form. char string[10] = "1234567890" ; long integer; // Base is 10 because we are converting to integer. integer = strtol (string, NULL, 10); printf ( "Number is %lu" , integer); } |
Output
Number is 1234567890
C
// C program to demonstrate working of strol() #include <stdio.h> #include <stdlib.h> int main() { char string[40] = "100 GeeksforGeeks" ; long integer; char * ptr; // strtol function to convert number in string form to // long integer with base 10 integer = strtol (string, &ptr, 10); printf ( "Integer part is %lu\n" , integer); printf ( "String part is %s\n" , ptr); return 0; } |
Output
Integer part is 100 String part is GeeksforGeeks
Method: Using atol() function
C
#include <stdlib.h> #include <stdio.h> int main() { long l; char *str; str = "349639 geeksforgeeks" ; l = atol (str); printf ( "l = %.ld\n" ,l); } |
Output
l = 349639
Method: Using ltoa()
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { long i = 1234; char buffer[100]; ltoa(i, buffer, 10); printf ( "string is %s\n" , buffer); return 0; } |
Output
string is 1234
Method: Without Inbuilt Function
C
// C program to demonstrate working of strol() #include <stdio.h> #include <stdlib.h> // Driver Code int main() { // To store Number in String form. char string[10] = "123456789" ; long integer = 0; int i = 0; // Until null character is encountered while (string[i] != '\0' ) { integer = (integer * 10) + (string[i] - '0' ); i++; } // Printing the number printf ( "Number is %lu" , integer); } |
Output
Number is 123456789
Please Login to comment...