itoa函数的实现

itoa的实现

(我的编译器是VS2013)
itoa()函数表示:把一个整形转换为相应的字符串;eg: 整形1234 转换为“1234”,整形-123转换为“-123”。

itoa代码实现

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//itoa------(将整形转换为字符串)


//字符串反转
char * reverse(char * str)
{
    char *head=str;//指向字符串首
    char *tail=str;//指向字符串尾
    while (*tail)//*tail!='\0'
    {
        ++tail;
    }
    --tail;
    char temp;
    while (head < tail)
    {
        temp = *head;
        *head++ = *tail;
        *tail-- = temp;
    }
    return str;
}

//my_itoa
char * my_itoa(int a)
{
    int n = a;
    if (a < 0)
    {
        a = -a;//如果是负数先转化为正数
    }
    static char str[100];//这里的str必须是静态变量或全局变量
    int i = 0;
    while (a>0)//从低位开始变为字符,最后进行翻转
    { 
        str[i++] = a % 10 + '0';//将数字转为字符串
        a = a / 10;
    }
    if (n < 0)//如果是负数加上‘-’号
    {
        str[i++] = '-';
    }
    str[i] = '\0';

    return reverse(str);
}

//测试代码块
int main()
{ 
    int a = 1234;
    cout << "原整形:" << a<<"  ";
    char *str1 = my_itoa(a);
    cout << "转为字符串:";
    while(*str1)
    {
        cout << *str1;
        ++str1;
    }
    cout << endl;

    int b = -123;
    cout << "原整形:" << b << "  ";
    char *str2 = my_itoa(b);
    cout << "转为字符串:";
    while (*str2)
    {
        cout << *str2;
        ++str2;
    }
    cout << endl;
    system("pause");
    return 0;
}

itoa 结果显示

这里写图片描述

atoi函数的实现


版权声明:本文为mm_hh原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。