c语言解析atoi函数:用于数字字符转数字

目录

1. 引言

2.atoi函数

3.使用demo


1. 引言

很多时候,我们都需要把数字形式的字符串进行数字运算,比如“123”,但是它们只不过是看起来像数字,本质上属于字符串,当我们如果自己写一个函数把这样的字符串拆分组装成数字,之后再用于运算,也是可以的。但是这么做,很麻烦。其实,在c语言库中已经给出了这样一个函数,即是atoi函数。

2.atoi函数

功能
atoi函数会从str字符串中解析数字字符,然后将它们转换为整数,并返回该整数值。如果字符串无法正确解析为整数,atoi函数将返回0。
头文件
<math.h> 或者 <stdlib.h>
函数原型
int atoi(const char *str);
入力参数
str:一个以ASCII表示的字符串,它包含要转换为整数的数字。

3.使用demo

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

int main(int argc, char* argv[])
{
    int re = 0;
    const char* demoChar = "80";
    printf("demoChar is %d, %d \n",demoChar[0],demoChar[1]);
    re = atoi(demoChar);
    printf("after atoi,the demoChar is %d \n",re);
    return 0;
}

ubutu环境下编译

gcc string_demo.cpp -o string_demo

运行

./string_demo

结果如下

root@xuehaiyang:/mnt/hgfs/99_github/cpp_demo# ./string_demo
demoChar is 56, 48 
after atoi,the demoChar is 80 

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青草地溪水旁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值