How to convert characters to numbers in the C language?

In the C language, you can use the atoi() function to convert a string to an integer. This function requires including the header file string.h.

The example code is shown below:

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

int main() {
    char str[] = "123";
    int num = atoi(str);
    printf("%d\n", num);
    return 0;
}

The output is:

123

Additionally, if you only need to convert a single character to a number, this can be achieved by subtracting the ASCII value of the character ‘0’. For example, the code to convert the character ‘5’ to the number 5 is as follows:

char c = '5';
int num = c - '0';
printf("%d\n", num);

The output result is:

5
bannerAds