溫馨提示×

C語言字符串怎么轉換為數字

小億
170
2023-12-21 09:15:24
欄目: 編程語言

在C語言中,可以使用標準庫函數atoi、atofsscanf將字符串轉換為數字。

  1. 使用atoi函數將字符串轉換為整數:
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    int num = atoi(str);
    printf("The converted number is: %d\n", num);

    return 0;
}
  1. 使用atof函數將字符串轉換為浮點數:
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "3.14";
    float num = atof(str);
    printf("The converted number is: %.2f\n", num);

    return 0;
}
  1. 使用sscanf函數從字符串中提取數字:
#include <stdio.h>

int main() {
    char str[] = "The price is $12.50";
    float price;
    
    sscanf(str, "The price is $%f", &price);
    printf("The converted number is: %.2f\n", price);

    return 0;
}

以上示例中,分別使用atoi、atofsscanf將字符串轉換為整數、浮點數和提取指定格式的數字。

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