convert string to int c
Converting a String to an Integer in C
To convert a string to an integer in C, you can use the atoi
function from the standard library. Here are the steps to convert a string to an integer:
Include the necessary header file:
c #include <stdlib.h>
Declare a string variable to hold the input:
c char str[] = "12345";
Use the
atoi
function to convert the string to an integer:c int num = atoi(str);
The atoi
function takes a string as input and returns the corresponding integer value. If the string cannot be converted to an integer, atoi
will return 0.
- Print the converted integer:
c printf("The converted integer is: %d\n", num);
This will display the converted integer value.
Here's the complete code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("The converted integer is: %d\n", num);
return 0;
}
This code will output:
The converted integer is: 12345
Please note that the atoi
function has some limitations. It will stop converting the string as soon as it encounters a non-digit character. If the string contains non-digit characters at the beginning, atoi
will return 0. If the string contains non-digit characters in the middle, atoi
will convert the digits before the non-digit characters and ignore the rest.