w3resource

C atoi() function

C atoi() function - Convert a string to an integer

The atoi() function is used to convert a character string to an integer value.

Syntax:

int atoi(const char *str)

Parameters:

Name Description Required /Optional
str String to be converted. Required

Return value from atoi()

  • Returns an integer value that is produced by interpreting the input characters as a number.
  • If the function cannot convert the input to a value of that type return value is 0.
  • The return value is undefined in the case of an overflow.

Example: atoi() function

The following example shows the usage of atoi() function.


#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
    int in_val;
    char *s;
    s = " -4938";
    printf("String value: %s",s);
    in_val= atoi(s); 
    printf("\nInteger value = %d\n",in_val);
    s = "+4938";
    printf("\nString value: %s",s);
    in_val= atoi(s); 
    printf("\nInteger value = %d\n",in_val);
    s = "4938";
    printf("\nString value: %s",s);
    in_val= atoi(s); 
    printf("\nInteger value = %d\n",in_val);
    s = "0038";
    printf("\nString value: %s",s);
    in_val= atoi(s); 
    printf("\nInteger value = %d\n",in_val);
    s = "003800";
    printf("\nString value: %s",s);
    in_val= atoi(s); 
    printf("\nInteger value = %d\n",in_val);
}

Output:

String value:  -4938
Integer value = -4938

String value: +4938
Integer value = 4938

String value: 4938
Integer value = 4938

String value: 0038
Integer value = 38

String value: 003800
Integer value = 3800

C Programming Code Editor:

Previous C Programming: C atof()
Next C Programming: C atol()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-atoi.php