The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer.
Syntax of atoi()
int atoi(const char strn);
Parameters
- The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent.
Return Value
- If strn is a valid input, then the function returns the equivalent integer number for the passed string number.
- If no valid conversion takes place, then the function returns zero.
Example
C++
#include <bits/stdc++.h>using namespace std;Â
int main(){Â Â Â Â int val;Â Â Â Â char strn1[] = "12546";Â
    val = atoi(strn1);    cout << "String value = " << strn1 << endl;    cout << "Integer value = " << val << endl;Â
    char strn2[] = "neveropen";    val = atoi(strn2);    cout << "String value = " << strn2 << endl;    cout << "Integer value = " << val << endl;Â
    return (0);}Â
// This code is contributed by shivanisinghss2110 |
C
#include <stdio.h>#include <stdlib.h>#include <string.h>Â
int main(){Â Â Â Â int val;Â Â Â Â char strn1[] = "12546";Â
    val = atoi(strn1);    printf("String value = %s\n", strn1);    printf("Integer value = %d\n", val);Â
    char strn2[] = "neveropen";    val = atoi(strn2);    printf("String value = %s\n", strn2);    printf("Integer value = %d\n", val);Â
    return (0);} |
Java
import java.util.*;Â
public class Main {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â Â Â Â Â Â Â Â int val;Â Â Â Â Â Â Â Â String strn1 = "12546";Â
        val = Integer.parseInt(strn1);        System.out.println("String value = " + strn1);        System.out.println("Integer value = " + val);Â
        String strn2 = "neveropen";        try {            val = Integer.parseInt(strn2);            System.out.println("String value = " + strn2);            System.out.println("Integer value = " + val);        }        catch (NumberFormatException e) {            val = 0;            System.out.println("String value = " + strn2);            System.out.println("Integer value = " + val);        }    }} |
Python3
def main():Â Â Â Â strn1 = "12546"Â Â Â Â val = int(strn1)Â Â Â Â print("String value = ", strn1)Â Â Â Â print("Integer value = ", val)Â
    strn2 = "neveropen"    try:        val = int(strn2)    except ValueError:        val = 0        print("String value = ", strn2)        print("Integer value = ", val)Â
Â
if __name__ == "__main__":Â Â Â Â main() |
C#
using System;Â
namespace neveropen {class Program {Â Â Â Â static void Main(string[] args)Â Â Â Â {Â Â Â Â Â Â Â Â String strn1 = "12546";Â Â Â Â Â Â Â Â int val = int.Parse(strn1);Â Â Â Â Â Â Â Â Console.WriteLine("String value = " + strn1);Â Â Â Â Â Â Â Â Console.WriteLine("Integer value = " + val);Â
        String strn2 = "neveropen";        try {            val = int.Parse(strn2);        }        catch (FormatException e) {            val = 0;            Console.WriteLine("String value = " + strn2);            Console.WriteLine("Integer value = " + val);        }    }}} |
Javascript
// Javascript code to convert string to integerlet val;let strn1 = "12546";Â
val = parseInt(strn1);console.log("String value = " + strn1);console.log("Integer value = " + val);Â
let strn2 = "neveropen";val = parseInt(strn2);console.log("String value = " + strn2);console.log("Integer value = " + val);Â
// This code is contributed by prasad264 |
String value = 12546 Integer value = 12546 String value = neveropen Integer value = 0
Complexity Analysis:
- Time Complexity: O(n), Only one traversal of the string is needed.
- Space Complexity: O(1), As no extra space is required.
Now let’s understand various ways in which one can create their own atoi() function supported by various conditions:
Approach 1
The following is a simple implementation of conversion without considering any special case.Â
- Initialize the result as 0.
- Start from the first character and update the result for every character.
- For every character update the answer as result = result * 10 + (s[i] – ‘0’)
Below is the implementation of the above approach:
C++
// A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std;Â
// A simple atoi() functionint myAtoi(char* str){    // Initialize result    int res = 0;Â
    // Iterate through all characters    // of input string and update result    // take ASCII character of corresponding digit and    // subtract the code from '0' to get numerical    // value and multiply res by 10 to shuffle    // digits left to update running total    for (int i = 0; str[i] != '\0'; ++i)        res = res * 10 + str[i] - '0';Â
    // return result.    return res;}Â
// Driver codeint main(){Â Â Â Â char str[] = "89789";Â
    // Function call    int val = myAtoi(str);    cout << val;    return 0;}Â
// This is code is contributed by rathbhupendra |
C
// Program to implement atoi() in C#include <stdio.h>Â
// A simple atoi() functionint myAtoi(char* str){    // Initialize result    int res = 0;Â
    // Iterate through all characters    // of input string and update result    // take ASCII character of corresponding digit and    // subtract the code from '0' to get numerical    // value and multiply res by 10 to shuffle    // digits left to update running total    for (int i = 0; str[i] != '\0'; ++i)        res = res * 10 + str[i] - '0';Â
    // return result.    return res;}Â
// Driver Codeint main(){Â Â Â Â char str[] = "89789";Â
    // Function call    int val = myAtoi(str);    printf("%d ", val);    return 0;} |
Java
// A simple Java program for// implementation of atoiclass GFG {Â
    // A simple atoi() function    static int myAtoi(String str)    {        // Initialize result        int res = 0;Â
        // Iterate through all characters        // of input string and update result        // take ASCII character of corresponding digit and        // subtract the code from '0' to get numerical        // value and multiply res by 10 to shuffle        // digits left to update running total        for (int i = 0; i < str.length(); ++i)            res = res * 10 + str.charAt(i) - '0';Â
        // return result.        return res;    }Â
    // Driver code    public static void main(String[] args)    {        String str = "89789";Â
        // Function call        int val = myAtoi(str);        System.out.println(val);    }}Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python program for implementation of atoiÂ
# A simple atoi() functionÂ
Â
def myAtoi(string):Â Â Â Â res = 0Â
    # Iterate through all characters of    # input string and update result    for i in range(len(string)):        res = res * 10 + (ord(string[i]) - ord('0'))Â
    return resÂ
Â
# Driver programstring = "89789"Â
# Function callprint(myAtoi(string))Â
# This code is contributed by BHAVYA JAIN |
C#
// A simple C# program for implementation// of atoiusing System;Â
class GFG {Â
    // A simple atoi() function    static int myAtoi(string str)    {        int res = 0; // Initialize resultÂ
        // Iterate through all characters        // of input string and update result        // take ASCII character of corresponding digit and        // subtract the code from '0' to get numerical        // value and multiply res by 10 to shuffle        // digits left to update running total        for (int i = 0; i < str.Length; ++i)            res = res * 10 + str[i] - '0';Â
        // return result.        return res;    }Â
    // Driver code    public static void Main()    {        string str = "89789";Â
        // Function call        int val = myAtoi(str);        Console.Write(val);    }}Â
// This code is contributed by Sam007. |
Javascript
<script>// A simple Javascript program for// implementation of atoiÂ
// A simple atoi() functionfunction myAtoi(str){    // Initialize result        let res = 0;          // Iterate through all characters        // of input string and update result        // take ASCII character of corresponding digit and        // subtract the code from '0' to get numerical        // value and multiply res by 10 to shuffle        // digits left to update running total        for (let i = 0; i < str.length; ++i)            res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);          // return result.        return res;}Â
// Driver codelet str = "89789";Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // Function calllet val = myAtoi(str);document.write(val);Â
Â
// This code is contributed by rag2127</script> |
89789
Complexity Analysis:
- Time Complexity: O(n), Only one traversal of the string is needed.
- Space Complexity: O(1), As no extra space is required.
Approach 2
This implementation handles the negative numbers.
- If the first character is ‘-‘ then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying the sign with it.
Below is the implementation of the above approach:
C++
// A C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std;Â
// A simple atoi() functionint myAtoi(char* str){    // Initialize result    int res = 0;Â
    // Initialize sign as positive    int sign = 1;Â
    // Initialize index of first digit    int i = 0;Â
    // If number is negative,    // then update sign    if (str[0] == '-') {        sign = -1;Â
        // Also update index of first digit        i++;    }Â
    // Iterate through all digits    // and update the result    for (; str[i] != '\0'; i++)        res = res * 10 + str[i] - '0';Â
    // Return result with sign    return sign * res;}Â
// Driver codeint main(){Â Â Â Â char str[] = "-123";Â
    // Function call    int val = myAtoi(str);    cout << val;    return 0;}Â
// This is code is contributed by rathbhupendra |
C
// A C program for// implementation of atoi#include <stdio.h>Â
// A simple atoi() functionint myAtoi(char* str){    // Initialize result    int res = 0;Â
    // Initialize sign as positive    int sign = 1;Â
    // Initialize index of first digit    int i = 0;Â
    // If number is negative,    // then update sign    if (str[0] == '-') {        sign = -1;Â
        // Also update index of first digit        i++;    }Â
    // Iterate through all digits    // and update the result    for (; str[i] != '\0'; ++i)        res = res * 10 + str[i] - '0';Â
    // Return result with sign    return sign * res;}Â
// Driver codeint main(){Â Â Â Â char str[] = "-123";Â
    // Function call    int val = myAtoi(str);    printf("%d ", val);    return 0;} |
Java
// Java program for// implementation of atoiclass GFG {Â
    // A simple atoi() function    static int myAtoi(char[] str)    {Â
        // Initialize result        int res = 0;Â
        // Initialize sign as positive        int sign = 1;Â
        // Initialize index of first digit        int i = 0;Â
        // If number is negative, then        // update sign        if (str[0] == '-') {            sign = -1;Â
            // Also update index of first            // digit            i++;        }Â
        // Iterate through all digits        // and update the result        for (; i < str.length; ++i)            res = res * 10 + str[i] - '0';Â
        // Return result with sign        return sign * res;    }Â
    // Driver code    public static void main(String[] args)    {        char[] str = "-123".toCharArray();Â
        // Function call        int val = myAtoi(str);        System.out.println(val);    }}Â
// This code is contributed by 29AjayKumar |
Python3
# Python program for implementation of atoiÂ
# A simple atoi() functionÂ
Â
def myAtoi(string):    res = 0    # initialize sign as positive    sign = 1    i = 0Â
    # if number is negative then update sign    if string[0] == '-':        sign = -1        i += 1Â
    # Iterate through all characters    # of input string and update result    for j in range(i, len(string)):        res = res*10+(ord(string[j])-ord('0'))Â
    return sign * resÂ
Â
# Driver codestring = "-123"Â
# Function callprint(myAtoi(string))Â
# This code is contributed by BHAVYA JAIN |
C#
// C# program for implementation of atoiusing System;Â
class GFG {Â
    // A simple atoi() function    static int myAtoi(string str)    {Â
        // Initialize result        int res = 0;Â
        // Initialize sign as positive        int sign = 1;Â
        // Initialize index of first digit        int i = 0;Â
        // If number is negative, then        // update sign        if (str[0] == '-') {            sign = -1;Â
            // Also update index of first            // digit            i++;        }Â
        // Iterate through all digits        // and update the result        for (; i < str.Length; ++i)            res = res * 10 + str[i] - '0';Â
        // Return result with sign        return sign * res;    }Â
    // Driver code    public static void Main()    {        string str = "-123";Â
        // Function call        int val = myAtoi(str);        Console.Write(val);    }}Â
// This code is contributed by Sam007. |
Javascript
<script>Â
    // JavaScript program for implementation of atoiÂ
    // A simple atoi() function    function myAtoi(str)    {          // Initialize result        var res = 0;          // Initialize sign as positive        var sign = 1;          // Initialize index of first digit        var i = 0;          // If number is negative, then        // update sign        if (str[0] == '-') {            sign = -1;              // Also update index of first            // digit            i++;        }          // Iterate through all digits        // and update the result        for (; i < str.length; ++i)            res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);          // Return result with sign        return sign * res;    }        // Driver code          var str = "-129";          var val=myAtoi(str);        document.write(val);Â
</script>Â <! --This code is contributed by nirajgusain5 --> |
-123
Complexity Analysis:
- Time Complexity: O(n), Only one traversal of the string is needed.
- Space Complexity: O(1), As no extra space is required.
Approach 3
Four corner cases need to be handled:
- Discard all leading whitespaces
- Sign of the number
- Overflow
- Invalid Input
Below are the steps for the above approach:
- To remove the leading whitespaces, run a loop and ignore the whitespaces until a character of the digit is reached.
- It keeps a sign variable to keep track of the sign of the number.
- It checks for valid input characters if all characters are from 0 to 9 and converts them into integers.
- If an overflow occurs and if the number is greater than or equal to INT_MAX/10, return INT_MAX if the sign is positive and return INT_MIN if the sign is negative.
The other cases are handled in previous approaches.Â
Dry Run:
Below is the implementation of the above approach:Â
C++
// A simple C++ program for// implementation of atoi#include <bits/stdc++.h>using namespace std;Â
int myAtoi(const char* str){Â Â Â Â int sign = 1, base = 0, i = 0;Â
    // if whitespaces then ignore.    while (str[i] == ' ') {        i++;    }Â
    // sign of number    if (str[i] == '-' || str[i] == '+') {        sign = 1 - 2 * (str[i++] == '-');    }Â
    // checking for valid input    while (str[i] >= '0' && str[i] <= '9') {        // handling overflow test case        if (base > INT_MAX / 10            || (base == INT_MAX / 10 && str[i] - '0' > 7)) {            if (sign == 1)                return INT_MAX;            else                return INT_MIN;        }        base = 10 * base + (str[i++] - '0');    }    return base * sign;}Â
// Driver Codeint main(){Â Â Â Â char str[] = "Â -123";Â
    // Functional Code    int val = myAtoi(str);    cout << " " << val;    return 0;}Â
// This code is contributed by shivanisinghss2110 |
C
// A simple C++ program for// implementation of atoi#include <limits.h>#include <stdio.h>Â
int myAtoi(const char* str){Â Â Â Â int sign = 1, base = 0, i = 0;Â
    // if whitespaces then ignore.    while (str[i] == ' ') {        i++;    }Â
    // sign of number    if (str[i] == '-' || str[i] == '+') {        sign = 1 - 2 * (str[i++] == '-');    }Â
    // checking for valid input    while (str[i] >= '0' && str[i] <= '9') {        // handling overflow test case        if (base > INT_MAX / 10            || (base == INT_MAX / 10 && str[i] - '0' > 7)) {            if (sign == 1)                return INT_MAX;            else                return INT_MIN;        }        base = 10 * base + (str[i++] - '0');    }    return base * sign;}Â
// Driver Codeint main(){Â Â Â Â char str[] = "Â -123";Â
    // Functional Code    int val = myAtoi(str);    printf("%d ", val);    return 0;}// This code is contributed by Yogesh shukla. |
Java
// A simple Java program for// implementation of atoiclass GFG {Â Â Â Â static int myAtoi(char[] str)Â Â Â Â {Â Â Â Â Â Â Â Â int sign = 1, base = 0, i = 0;Â
        // if whitespaces then ignore.        while (str[i] == ' ') {            i++;        }Â
        // sign of number        if (str[i] == '-' || str[i] == '+') {            sign = 1 - 2 * (str[i++] == '-' ? 1 : 0);        }Â
        // checking for valid input        while (i < str.length && str[i] >= '0'               && str[i] <= '9') {Â
            // handling overflow test case            if (base > Integer.MAX_VALUE / 10                || (base == Integer.MAX_VALUE / 10                    && str[i] - '0' > 7)) {                if (sign == 1)                    return Integer.MAX_VALUE;                else                    return Integer.MIN_VALUE;            }            base = 10 * base + (str[i++] - '0');        }        return base * sign;    }Â
    // Driver code    public static void main(String[] args)    {        char str[] = " -123".toCharArray();Â
        // Function call        int val = myAtoi(str);        System.out.printf("%d ", val);    }}Â
// This code is contributed by 29AjayKumar |
Python3
# A simple Python3 program for# implementation of atoiimport sysÂ
Â
def myAtoi(Str):Â
    sign, base, i = 1, 0, 0Â
    # If whitespaces then ignore.    while (Str[i] == ' '):        i += 1Â
    # Sign of number    if (Str[i] == '-' or Str[i] == '+'):        sign = 1 - 2 * (Str[i] == '-')        i += 1Â
    # Checking for valid input    while (i < len(Str) and           Str[i] >= '0' and Str[i] <= '9'):Â
        # Handling overflow test case        if (base > (sys.maxsize // 10) or            (base == (sys.maxsize // 10) and                (Str[i] - '0') > 7)):            if (sign == 1):                return sys.maxsize            else:                return -(sys.maxsize)Â
        base = 10 * base + (ord(Str[i]) - ord('0'))        i += 1Â
    return base * signÂ
Â
# Driver CodeStr = list(" -123")Â
# Functional Codeval = myAtoi(Str)Â
print(val)Â
# This code is contributed by divyeshrabadiya07 |
C#
// A simple C# program for implementation of atoiusing System;Â
class GFG {Â Â Â Â static int myAtoi(char[] str)Â Â Â Â {Â Â Â Â Â Â Â Â int sign = 1, Base = 0, i = 0;Â
        // if whitespaces then ignore.        while (str[i] == ' ') {            i++;        }Â
        // sign of number        if (str[i] == '-' || str[i] == '+') {            sign = 1 - 2 * (str[i++] == '-' ? 1 : 0);        }Â
        // checking for valid input        while (i < str.Length && str[i] >= '0'               && str[i] <= '9') {Â
            // handling overflow test case            if (Base > int.MaxValue / 10                || (Base == int.MaxValue / 10                    && str[i] - '0' > 7)) {                if (sign == 1)                    return int.MaxValue;                else                    return int.MinValue;            }            Base = 10 * Base + (str[i++] - '0');        }        return Base * sign;    }Â
    // Driver code    public static void Main(String[] args)    {        char[] str = " -123".ToCharArray();        int val = myAtoi(str);        Console.Write("{0} ", val);    }}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>// A simple JavaScript program for// implementation of atoi    function myAtoi(str)   {    var sign = 1, base = 0, i = 0;         // if whitespaces then ignore.    while (str[i] == ' ')     {        i++;    }         // sign of number    if (str[i] == '-' || str[i] == '+')     {        sign = 1 - 2 * (str[i++] == '-');    }       // checking for valid input    while (str[i] >= '0' && str[i] <= '9')     {        // handling overflow test case        if (base > Number.MAX_VALUE/ 10            || (base == Number.MAX_VALUE / 10             && str[i] - '0' > 7))         {            if (sign == 1)                return Number.MAX_VALUE;            else                return Number.MAX_VALUE;        }        base = 10 * base + (str[i++] - '0');    }    return base * sign;}Â
    // Driver code        var str = " -123";               // Function call        var val = myAtoi(str);        document.write(" ", val);     // This code is contributed by shivanisinghss2110</script> |
-123
Complexity Analysis:
- Time Complexity: O(n), Only one traversal of the string is needed.
- Space Complexity: O(1), As no extra space is required.
Related Articles:
Exercise:
Write your won atof() that takes a string (which represents a floating point value) as an argument and returns its value as double.
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Â
If you like neveropen and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

