String Conversion using atoi( )
The atoi() function in C takes a character array or string literal as an argument and returns its value in an integer. It is defined in the <stdlib.h> header file.
If you observe atoi() a little closer you will find out that it stands for:
Example:
C
// C program to demonstrate the // functioning of the atoi() function #include <stdio.h> #include <stdlib.h> int main() { char * str1 = "141" ; char * str2 = "3.14" ; // explicit type casting int res1 = atoi (str1); // explicit type casting int res2 = atoi (str2); printf ( "atoi(%s) is %d \n" , str1, res1); printf ( "atoi(%s) is %d \n" , str2, res2); return 0; } |
atoi(141) is 141 atoi(3.14) is 3
Atoi behaves a bit differently for string. Let’s check how:
Example:
C
// C Program to implement // Atoi function with char array #include <stdio.h> #include <stdlib.h> int main() { char * str1 = "Geek 12345" ; char * str2 = "12345 Geek" ; int num1 = atoi (str1); int num2 = atoi (str2); printf ( "%d is of '%s'\n" , num1, str1); printf ( "%d is of '%s'\n" , num2, str2); return 0; } |
0 is of 'Geek 12345' 12345 is of '12345 Geek'
Explanation:
- “Geek 12345” here ‘Geek’ is the first word so the answer will be : 0 (No number)
- “12345 Geek” here ‘12345’ is the first word so the answer will be: 12345
Convert String to int in C
Converting string to int is a reoccurring task in the programming world. Despite being a simple task, many coders either fail or get confused while doing this. Conversion is mostly done so that we can perform operations over numbers that are stored as strings.
Example:
str=”163″
number=163
C is a strongly typed language. We’ll get an error if we try to input a value that isn’t acceptable with the data type. Not just in inputs but we will get an error while performing operations.
There are 3 methods to convert a string to int which are as follows:
- Using atoi( )
- Using Loops
- Using sscanf()
Contact Us