C Reference function atoi() convert a string to an integer

This function of stdlib will convert a string to an integer.

Usage of atoi():

int atoi ( const char * str );

Parameters:

C string str interpreting its content as a integer. White-spaces are discarded until the first non-whitespace character is found.

Return value:

The function returns the converted integral number as an int value, if successful. If no valid conversion could be performed then an zero value is returned. If the value is out of range then INT_MAX or INT_MIN is returned.

Source code example of atoi():


	#include<stdio.h>
	#include<stdlib.h>

	int main ()
	{
		int i;
		char buffer [256];

		printf ("Enter a number: ");
		fgets (buffer, 256, stdin);

		i = atoi (buffer);
		printf ("The value entered is %d.",i);

		return 0;
	}

Output of the atoi example program above:


	Enter a number:12

	The value entered is 12.

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 5 responses to “C Reference function atoi() convert a string to an integer”

Why not let us know what you think by adding your own comment!

  1. sarah on March 17th, 2012:

    best answer i got here……..thankyou!!!

  2. sarah on March 17th, 2012:

    i didnt understand the fgets arguments..

  3. sarah on March 17th, 2012:

    i tried using atoi but geting an error saying TYPE MISMATCH IN PARAMETER ‘_S’ IN CALL TO ATOL….can anybody help me out?

  4. rebecca on October 13th, 2012:

    I mean for example if the user will input the word “eleven” the output must be 11?

  5. Sagar on January 10th, 2013:

    @rebecca: NO! It’s just that, if a number is stored in form of string, atoi() will convert it into an integer, so now you can perform integral operations on it.
    eg: char *str = “11″; //you cannot perfrom mathematical operations on str
    int x = atoi(str); //now x will contain numerical value 11

Leave a Reply: