首页 > 解决方案 > 如何最好地实现 itoa 和 atoi?

问题描述

C/C++ 库带有两个函数,即“itoa”和“atoi”——前者将整数值转换为字符数组。后者对包含数值的字符串数组执行反之亦然。任一函数中的数值可以是正整数或负整数。

我实现的功能如下:- itoa 功能

#include <iostream>
#include <algorithm>

void my_itoa(int num, char* str) 
{
    bool isNeg=false;
    if(num < 0)
      isNeg = true;

    int idx = 0;
    do {
       int j = num % 10;
       j = j < 0 ? j * -1 : j ;
       str[idx++]=j+48;
       num=num/10;
    } while (num!=0);
    if(isNeg)
       str[idx++]='-';
    str[idx]='\0';

    std::reverse(str, str+idx);
}

atoi 函数

void my_atoi(char* str,int& i) 
{
  bool isNeg = false;
  if(*str == '-') {
    isNeg=true;
    str++;
  }
  i=0;
  while(*str!='\0') {
    i =i*10 + (*str - 48);
    str++;
  }
  if(isNeg) 
    i=i*-1;
}

驱动程序代码

int main()
{
    char str[100];
    my_itoa(-1234, str);
    std::cout << "Str =" << str << std::endl;
    int j=0;
    my_atoi(str,j);
    std::cout << "j= " << j << std::endl;
    return 0;
}

我想看看如何为他们获得生产质量代码 - 因为上面的性能并没有真正达到标准库的标准。

标签: data-structurestype-conversion

解决方案


推荐阅读