C++ Program To Write Your Own atoi()
Last Updated :
18 Aug, 2023
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);
}
|
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:
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++
#include <bits/stdc++.h>
using namespace std;
int myAtoi( char * str)
{
int res = 0;
for ( int i = 0; str[i] != '' ; ++i)
res = res * 10 + str[i] - '0' ;
return res;
}
int main()
{
char str[] = "89789" ;
int val = myAtoi(str);
cout << val;
return 0;
}
|
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++
#include <bits/stdc++.h>
using namespace std;
int myAtoi( char * str)
{
int res = 0;
int sign = 1;
int i = 0;
if (str[0] == '-' ) {
sign = -1;
i++;
}
for (; str[i] != '' ; i++)
res = res * 10 + str[i] - '0' ;
return sign * res;
}
int main()
{
char str[] = "-123" ;
int val = myAtoi(str);
cout << val;
return 0;
}
|
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.
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++
#include <bits/stdc++.h>
using namespace std;
int myAtoi( const char * str)
{
int sign = 1, base = 0, i = 0;
while (str[i] == ' ' )
{
i++;
}
if (str[i] == '-' || str[i] == '+' )
{
sign = 1 - 2 * (str[i++] == '-' );
}
while (str[i] >= '0' && str[i] <= '9' )
{
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;
}
int main()
{
char str[] = " -123" ;
int val = myAtoi(str);
cout << " " << val;
return 0;
}
|
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!
Similar Reads
C++ Program to Print Your Own Name
Printing your own name means displaying your name on the computer screen. In this article, we will learn how to print your own name using a C++ program. Examples Input: name = "Anmol"Output: AnmolExplanation: Given name is printed on the output screen. Input: name = "Alex"Output: AlexExplanation: Gi
3 min read
C++ program to read file word by word
Given a text file, extract words from it. In other words, read the content of file word by word. Example : Input: And in that dream, we were flying. Output: And in that dream, we were flying. Approach : 1) Open the file which contains string. For example, file named "file.txt" contains a string "gee
1 min read
How to Take Operator as Input in C++?
Operators are symbols that specify some kind of operation. In C++, we sometimes need to take operators as user input mainly to perform mathematical operations. In this article, we will learn how to take operators as user input in C++. Operators as Input in C++To take operators (like +,-,*,/ etc) as
2 min read
C++ Program For String to Long Conversion
In this article, we will learn how to convert strings to long in C++. For this conversion, there are 3 ways as follows: Using stol()Using stoul()Using atol() Let's start by discussing each of these methods in detail. Example: Input: s1 = "20" s2 = "30" Output: s1 + s2 long: 50 1. Using stol() In C++
3 min read
C++ Program to Swap Two Numbers
Swapping numbers is the process of interchanging their values. In this article, we will learn algorithms and code to swap two numbers in the C++ programming language. 1. Swap Numbers Using a Temporary VariableWe can swap the values of the given two numbers by using another variable to temporarily st
4 min read
C++ Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
7 min read
C++ Program to Find Diagonal of a Rectangle
Given two positive integers i.e, the length and breadth of the rectangle, the task is to find the length of the Diagonal of a Rectangle. Example: Input: length=4 breadth=3 output: The Diagonal is 5 The diagonal of a rectangle is sqrt (a*a+ b*b) C/C++ Code // C++ Program to Find Diagonal of a Rectang
1 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 Convert String to Integer
Given a string of digits, the task is to convert the string to an integer. Examples: Input : str = "12345" Output : 12345 Input : str = "876538"; Output : 876538 Input : str = "0028"; Output : 28 C/C++ Code // C++ program to convert String into Integer #include <bits/stdc++.h> using namespace
1 min read
How to Reverse a Word Using Stack in C++?
In C++, we have a stack data structure that follows the Last In First Out (LIFO) principle. In this article, we will learn how to reverse a word using a stack in C++. Example: Input:word = "GeeksforGeeks"Output:Reversed Word: skeeGrofskeeGReverse a String Using Stack in C++To reverse a word using a
2 min read