Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
C++ Program To Write Your Own atoi()
Next article icon

C++ Program To Write Your Own atoi()

Last Updated : 18 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:  

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[] = "GeeksforGeeks";     val = atoi(strn2);     cout <<"String value = " << strn2 << endl;     cout <<"Integer value = " << val <<endl;      return (0); }  // This code is contributed by shivanisinghss2110 

Output
String value = 12546  Integer value = 12546  String value = GeeksforGeeks  Integer value = 0

Time Complexity : O(N)

Auxiliary Space : O(1) , as no extra space is needed.

Now let's understand various ways in which one can create their own atoi() function supported by various conditions:

Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

Approach 1: Following is a simple implementation of conversion without considering any special case. 

  • Initialize the result as 0.
  • Start from the first character and update result for every character.
  • For every character update the answer as result = result * 10 + (s[i] - '0')
C++
// A simple C++ program for // implementation of atoi #include <bits/stdc++.h> using namespace std;  // A simple atoi() function int 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] != ''; ++i)         res = res * 10 + str[i] - '0';      // return result.     return res; }  // Driver code int main() {     char str[] = "89789";        // Function call     int val = myAtoi(str);     cout << val;     return 0; }  // This is code is contributed by rathbhupendra 

Output
89789


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 sign with it. 

C++
// A C++ program for // implementation of atoi #include <bits/stdc++.h> using namespace std;  // A simple atoi() function 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 (; str[i] != ''; i++)         res = res * 10 + str[i] - '0';      // Return result with sign     return sign * res; }  // Driver code int main() {     char str[] = "-123";      // Function call     int val = myAtoi(str);     cout << val;     return 0; }  // This is code is contributed by rathbhupendra 

Output
-123


Approach 3: This implementation handles various type of errors. If str is NULL or str contains non-numeric characters then return 0 as the number is not valid. 


Output
 -134

Approach 4: Four corner cases needs to be handled: 

  • Discards all leading whitespaces
  • Sign of the number
  • Overflow
  • Invalid input

To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then 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 Code int main() {     char str[] = "  -123";        // Functional Code     int val = myAtoi(str);     cout <<" "<< val;     return 0; }  // This code is contributed by shivanisinghss2110 

Output
 -123

Complexity Analysis for all the above Approaches: 

  • Time Complexity: O(n). 
    Only one traversal of string is needed.
  • Space Complexity: O(1). 
    As no extra space is required.

Recursive program for atoi().

Exercise: 
Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.

Please refer complete article on Write your own atoi() for more details!


Next Article
C++ Program To Write Your Own atoi()

K

kartik
Improve
Article Tags :
  • Strings
  • C++ Programs
  • DSA
  • Microsoft
  • Amazon
  • Adobe
  • Morgan Stanley
  • Payu
  • Code Brew
Practice Tags :
  • Adobe
  • Amazon
  • Code Brew
  • Microsoft
  • Morgan Stanley
  • Payu
  • Strings

Similar Reads

    Structure of C++ Program
    The C++ program is written using a specific template structure. The structure of the program written in C++ language is as follows: Documentation Section:This section comes first and is used to document the logic of the program that the programmer going to code.It can be also used to write for purpo
    5 min read
    String C/C++ Programs
    C program to swap two StringsC Program to Sort an array of names or stringsC Program to Check if a Given String is PalindromeC/C++ Program for Return maximum occurring character in the input stringC/C++ Program for Remove all duplicates from the input string.C/C++ Program for Print all the duplicate
    3 min read
    C++ Program to Create a Temporary File
    Here, we will see how to create a temporary file using a C++ program. Temporary file in C++ can be created using the tmpfile() method defined in the <cstdio> header file. The temporary file created has a unique auto-generated filename. The file created is opened in binary mode and has access m
    2 min read
    C++ Program For String to Double Conversion
    There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++. Methods to Convert String to Double We can convert String to Double in C++ using the following methods: Using stod() Fun
    3 min read
    C++ Program to Make a Simple Calculator
    A simple calculator is a device used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It makes arithmetic calculations easier and faster. In this article, we will learn how to code a simple calculator using C++.ExamplesInput: Enter an operator (+, -
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences