How can C language convert a string into a number?

In the C programming language, there are several functions available to convert a string to a numerical type.

  1. Converts a string to an integer.
  2. converts a string to an integer
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    int num = atoi(str);
    printf("转换后的整数为:%d\n", num);
    return 0;
}
  1. converts a string to a floating point number
  2. Converts a string representing a number to a floating-point value.
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "3.14";
    float num = atof(str);
    printf("转换后的浮点数为:%f\n", num);
    return 0;
}
  1. Parse a string using the function sscanf().
  2. Reads formatted input from a string.
#include <stdio.h>

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

When converting strings to numbers, it is important to pay attention to the format of the string and the desired data type for conversion.

bannerAds