Linux 拨号vps windows公众号手机端

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

lewis 6年前 (2019-11-28) 阅读数 12 #程序编程
文章标签 c语言

在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函数更加灵活,可以处理更多的异常情况,比如字符串中包含非数字字符。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门