温馨提示×

c语言字符串转数字如何实现

小亿
82
2024-04-26 14:05:48
栏目: 编程语言

在C语言中,可以使用库函数atoistrtol来实现字符串转换为数字的功能。

  1. 使用atoi函数:
#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函数:
#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;
}

这两种方法都可以将字符串转换为对应的整数,但是strtol函数更加灵活,可以处理更多的异常情况,比如字符串中包含非数字字符。

0