溫馨提示×

c語言字符串轉數字的方法是什么

小億
102
2023-12-12 17:03:41
欄目: 編程語言

在C語言中,可以使用庫函數atoi()將字符串轉換為整數,atof()將字符串轉換為浮點數。這兩個函數都位于stdlib.h頭文件中。

使用atoi()函數:

#include <stdlib.h>

int atoi(const char *str);

示例代碼:

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

int main() {
    const char *str = "12345";
    int num = atoi(str);
    
    printf("The converted number is: %d\n", num);
    
    return 0;
}

使用atof()函數:

#include <stdlib.h>

double atof(const char *str);

示例代碼:

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

int main() {
    const char *str = "3.14";
    double num = atof(str);
    
    printf("The converted number is: %f\n", num);
    
    return 0;
}

需要注意的是,如果字符串無法轉換為相應的數字類型,atoi()atof()函數將返回0。所以在實際應用中,應該確保字符串的格式正確,或者使用額外的錯誤處理機制。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女