
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Write your own memcpy() in C
- Write your own memcpy() and memmove() in C++
- Write your own strcmp that ignores cases in C++
- How to write your own LaTeX preamble in Matplotlib?
- How to write your own header file in C?\n
- Build Your Own Botnet
- Implement your own itoa() in C
- Can you build your own sundial?
- How will implement Your Own sizeof in C
- Making your own custom filter tags in Django
- Describe the ‘Greenhouse Effect’ in your own words.
- Can you own Crypto in your Roth IRA
- Implement your own sizeof operator using C++
- Print with your own font using Python?
- Print with your own font using C#
