C++ Programming/Code/Standard C Library/Functions/atoi

From Wikibooks, open books for an open world
Jump to: navigation, search
atoi[edit]
Syntax
#include <cstdlib>
int atoi( const char *str );

The atoi() function converts str into an integer, and returns that integer. str should start with a whitespace or some sort of number, and atoi() will stop reading from str as soon as a non-numerical character has been read. For example:

int i;
i = atoi( "512" );
i = atoi( "512.035" );
i = atoi( "   512.035" );
i = atoi( "   512+34" );
i = atoi( "   512 bottles of beer on the wall" );

All five of the above assignments to the variable i would result in it being set to 512.

If the conversion cannot be performed, then atoi() will return zero:

int i = atoi( " does not work: 512" );  // results in i == 0
Related topics
atof - atol
(Standard C I/O) sprintf