溫馨提示×

c語言字符串轉數(shù)字如何實現(xiàn)

小億
84
2024-04-26 14:05:48
欄目: 編程語言

在C語言中,可以使用庫函數(shù)atoistrtol來實現(xiàn)字符串轉換為數(shù)字的功能。

  1. 使用atoi函數(shù):
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    int num = atoi(str);
    printf("The number is: %d\n", num);
    return 0;
}
  1. 使用strtol函數(shù):
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    char *endptr;
    long num = strtol(str, &endptr, 10);
    if (*endptr != '\0') {
        printf("Invalid number\n");
    } else {
        printf("The number is: %ld\n", num);
    }
    return 0;
}

這兩種方法都可以將字符串轉換為對應的整數(shù),但是strtol函數(shù)更加靈活,可以處理更多的異常情況,比如字符串中包含非數(shù)字字符。

0