Atoi() function in C
×


Atoi() function in C

28

 The atoi() function in C is used to convert a string to an integer.

 It scans the initial part of the string until it encounters a non-numeric character or the end of the string.

 It then converts this portion of the string to an integer.

Syntax of atoi() function in C

int atoi(const char *str);

Parameters:

 str: A pointer to the null-terminated string that is to be converted to an integer.

Return Value:

 The atoi() function returns the converted integer value of the initial portion of the string.

 If the string does not contain any valid integer or if the first character is not a digit, it returns 0.

Examples:

Basic atoi() Example:

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

int main() {
    const char *str = "12345";
    int num = atoi(str);

    printf("Converted integer: %d\n", num);

    return 0;
}
	

Output:

Converted integer: 12345

atoi() with Invalid Input:

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

int main() {
    const char *str = "abc123";
    int num = atoi(str);

    printf("Converted integer: %d\n", num);

    return 0;
}
	

Output:

Converted integer: 0

atoi() with Negative Number:

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

int main() {
    const char *str = "-678";
    int num = atoi(str);

    printf("Converted integer: %d\n", num);

    return 0;
}
	

Output:

 integer: -678

 The atoi() function is defined in the stdlib.h header file.

 It stops the conversion when it encounters the first non-numeric character.

 For more robust string-to-integer conversions, consider using strtol() which provides better error handling.

 These examples demonstrate the usage of the atoi() function in C to convert strings to integers.

 The output shows the converted integer values for valid and invalid string inputs.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments