How can C language strings be converted to numbers?

In C language, you can use library functions like atoi(), atof(), sscanf(), etc. to convert strings to numbers.

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

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

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

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

All three methods can be used to convert a string to a number, the choice of which method to use depends on the specific requirements and format of the string.

bannerAds