atoi() - Utility Function

How is Utility function "atoi()" used in C++?
How to convert a string to integer value?


atoi() is a Utility Function that converts a string into a integer value. The string must contain a integer value, the rest of the string character are terminated by white space, punctuation, characters. If an integer is not found the result may be undefined, but in most scenarios will return 0.


int atoi(const char *str);

Example :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
int a;
char arr [20];
printf ( "Enter a string with a integer: " );
gets ( arr );
a = atoi ( arr );
printf ("The entered value is:: %d\n", a );
printf ("The bytes occupied is:: %d\n", sizeof(a));
return 0;

Result :

Enter a string with a integer: 3err
The entered value is:: 3
The bytes occupied is:: 4

In the above example atoi() is used to convert the string into integer, by terminating the string "3err" as soon as character "e" is found, then integer 3 is returned.

C++ Tutorial

Ask Questions

Ask Question