atoi函数——将字符串转为整形

                   

atoi()函数

atoi():int atoi(const char *str );

功能:把字符串转换成整型数。

str:要进行转换的字符串

返回值:每个函数返回 int 值,此值由将输入字符作为数字解析而生成。 如果该输入无法转换为该类型的值,则atoi的返回值为 0。

说明:当第一个字符不能识别为数字时,函数将停止读入输入字符串。



  
  
  1. #include<iostream>
  2. using namespace std;
  3. int atoi_my(const char *str)
  4. {
  5.   int s= 0;
  6.   bool falg= false;
  7.  
  8.   while(*str== ' ')
  9.  {
  10.   str++;
  11.  }
  12.   if(*str== '-'||*str== '+')
  13.  {
  14.    if(*str== '-')
  15.   falg= true;
  16.   str++;
  17.  }
  18.   while(*str>= '0'&&*str<= '9')
  19.  {
  20.   s=s* 10+*str- '0';
  21.   str++;
  22.    if(s< 0)
  23.   {
  24.    s= 2147483647;
  25.     break;
  26.   }
  27.  }
  28.   return s*(falg? -1: 1);
  29. }
  30. int main()
  31. {
  32.   char *s1= "333640";
  33.   char *s2= "-12345";
  34.   char *s3= "123.3113";
  35.   char *s4= "-8362865623872387698";
  36.   char *s5= "+246653278";
  37.   int sum1=atoi(s1);
  38.   int sum_1=atoi_my(s1);
  39.   int sum2=atoi(s2);
  40.   int sum_2=atoi_my(s2);
  41.   int sum3=atoi(s3);
  42.   int sum_3=atoi_my(s3);
  43.   int sum4=atoi(s4);
  44.   int sum_4=atoi_my(s4);
  45.   int sum5=atoi(s5);
  46.   int sum_5=atoi_my(s5);
  47.   cout<< "atoi:  :"<<sum1<< endl;
  48.   cout<< "atoi_my:"<<sum_1<< endl;
  49.   cout<< "atoi:  :"<<sum2<< endl;
  50.   cout<< "atoi_my:"<<sum_2<< endl;
  51.   cout<< "atoi:  :"<<sum3<< endl;
  52.   cout<< "atoi_my:"<<sum_3<< endl;
  53.   cout<< "atoi:  :"<<sum4<< endl;
  54.   cout<< "atoi_my:"<<sum_4<< endl;
  55.   cout<< "atoi:  :"<<sum5<< endl;
  56.   cout<< "atoi_my:"<<sum_5<< endl;
  57.  system( "pause");
  58.   return 0;
  59. }
运行结果如下:

               
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值