How to convert a string to a number in the C language?

In the C language, you can convert a string to an integer using the atoi function. The prototype of the atoi function is as follows:

int atoi(const char *str);

In this case, str is the string to be converted, and the function will convert the numerical part of the string to an integer and return it.

The example code is shown below:

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

int main() {
    char str[] = "1234";
    int num = atoi(str);
    printf("转换后的整数为:%d\n", num);
    
    return 0;
}

Output:

转换后的整数为:1234

It is important to note that the atoi function will automatically ignore any non-numeric characters in a string and return the valid numeric part. If the string cannot be correctly converted to an integer, it will return 0. If the number represented by the string exceeds the range of integers, the result may be inaccurate. For a more precise conversion, consider using the strtol function.

bannerAds