Write your own atoi() in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 17-Apr-2020 13:10:05
Advertisements