itoa(整型转字符型)与atoi(字符转整型)

itoa

代码:

#include<iostream>
using namespace std;


void int2str(int n,char* str)
{
char buf[10] = " ";
int len = 0;
int temp = n<0?-n:n;
int i = 0;
if(str == NULL)
{
return ;
}
while(temp)
{
buf[i++] = (temp%10)+'0';
temp = temp/10;
}
len  = n<0?++i:i;
str[i] = 0;
while(1)
{
i--;
if(buf[len-i-1] == 0)
break;
str[i] = buf[len-i-1];


}
if(i == 0)
str[i] = '-';



int main()
{
int n = 123;
char str[10];
int2str(123,str);
cout<<str<<endl;
return 0;
}


atoi

代码:

1    #include <iostream>
2    using namespace std;
3  
4    int str2int(const char *str)
5    {
6        int temp = 0;
7        const char *ptr = str;  //ptr保存str字符串开头
8  
9        if (*str == '-' || *str == '+')  //如果第一个字符是正负号,
10       {                      //则移到下一个字符
11           str++;
12       }
13       while(*str != 0)
14       {
15           if ((*str < '0') || (*str > '9'))  //如果当前字符不是数字
16           {                       //则退出循环
17               break;
18           }
19           temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值
20           str++;      //移到下一个字符
21       }  
22       if (*ptr == '-')     //如果字符串是以“-”开头,则转换成其相反数
23       {
24           temp = -temp;
25       }
26 
27       return temp;
28   }
29 
30   int main()
31   {
32       int n = 0;  
33       char p[10] = "";
34 
35       cin.getline(p, 20);   //从终端获取一个字符串
36       n = str2int(p);      //把字符串转换成整型数
37      
38       cout << n << endl;
39 
40       return 0;
41   }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值