Convert a String to an Integer in C
In C, we can convert a string to an integer using functions like atoi(), strtol(), and sscanf(). These functions help parse numerical values from a string representation and store them as an integer type.
In this tutorial, we will cover different methods to convert a string to an integer with step-by-step explanations and examples.
Methods to Convert a String to an Integer
1. Using atoi() Function to Convert a String to an Integer
The atoi() function (ASCII to integer) is a simple method to convert a string to an integer. It is part of the stdlib.h library. However, it does not provide error handling for invalid inputs.
main.c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("Converted integer: %d\n", num);
return 0;
}
Explanation:
- We declare a character array
str[]containing the numeric string"12345". - The
atoi()function fromstdlib.hconverts the string into an integer and stores it innum. - The converted integer is printed using
printf().
Output:
Converted integer: 12345
2. Using strtol() for Error Handling While Convert a String to an Integer
The strtol() (string to long) function is a safer alternative to atoi(). It allows error handling and supports different number bases.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
char str[] = "98765";
char *endptr;
long num = strtol(str, &endptr, 10);
if (*endptr != '\0') {
printf("Conversion error, non-numeric characters found: %s\n", endptr);
} else {
printf("Converted integer: %ld\n", num);
}
return 0;
}
Explanation:
- We declare a character array
str[]containing the numeric string"98765". - The
strtol()function converts the string into a long integer and stores it innum. - The
endptrpointer checks if any invalid characters are present after the number. - If
*endptris not'\0', it means the string contains non-numeric characters, and an error message is printed.
Output:
Converted integer: 98765
3. Using sscanf() to Convert a String to an Integer
The sscanf() function can also be used to convert a string to an integer, similar to formatted input reading.
main.c
#include <stdio.h>
int main() {
char str[] = "54321";
int num;
if (sscanf(str, "%d", &num) == 1) {
printf("Converted integer: %d\n", num);
} else {
printf("Conversion failed.\n");
}
return 0;
}
Explanation:
- We declare a character array
str[]containing the numeric string"54321". - The
sscanf()function reads the string and converts it into an integer stored innum. - If conversion is successful, it prints the integer; otherwise, it displays a failure message.
Output:
Converted integer: 54321
Conclusion
We explored different methods to convert a string to an integer in C:
atoi(): Simple and fast but lacks error handling.strtol(): Provides error handling and supports different number bases.sscanf(): Useful for extracting multiple values from a string.
For better safety and error handling, strtol() is recommended over atoi().
