
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write Your Own ATOI in C++
atoi() function in c programming language is used to handle string to integer conversion. The function takes a string as an input and returns the value in integer type.
Syntax
int atoi(const char string)
Parameters Accepted − The atio() function accepted a string as an input which will be converted into integer equivalent.
Return type − the function returns an integer value. The value will be the integer equivalent for a valid string otherwise 0 will be returned.
Implementation of atoi() function −
We take each character of the string and make the integer by adding the number to the previous result multiplied by 10.
For negative integers, we will check if the first character of a string in -, we will multiple the final result with -1.
We will check for a valid string by checking if each character lies between 0 to 9.
Program to show the implementation of our solution,
Example
#include <iostream> using namespace std; bool isNumericChar(char x) { return (x >= '0' && x <= '9') ? true : false; } int myAtoi(char* str) { if (*str == '\0') return 0; int result = 0; int sign = 1; int i = 0; if (str[0] == '-') { sign = -1; i++; } for (; str[i] != '\0'; ++i) { if (isNumericChar(str[i]) == false) return 0; result = result * 10 + str[i] - '0'; } return sign * result; } int main() { char string[] = "-32491841"; int intVal = myAtoi(string); cout<<"The integer equivalent of the given string is "<<intVal; return 0; }
Output
The integer equivalent of the given string is -32491841