Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

引子

自己实现一下atoi()和itoa() 这2个函数

实现

my_itoa.cpp

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
char *  my_itoa( int value, char * str, int base ){
    char array[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    bool is_minus = false;
    if(value<0){
        is_minus = true;
        value = - value;
    }
    //buffer
    char buffer[256];
    int i=0,j=0;
    int temp;
    while(value){
        temp =value%base;
        buffer[i++]=array[temp];
        value = value/base;
    }
    //cout<<buffer<<endl;
    if(is_minus){
        str[j++] = '-';
    }
    while(--i>=0){
        str[j++]=buffer[i];
    }
    str[j]='\0';
    return str;
}

int main ()
{
  int i;
  char buffer [33];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  my_itoa (i,buffer,10);
  printf ("decimal: %s\n",buffer);
  itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  my_itoa (i,buffer,16);
  printf ("hexadecimal: %s\n",buffer);
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  my_itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);
  return 0;
}

my_atoi.cpp

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
bool is_whitespace(char ch){
    if(ch == ' '||ch == '\t'){
        return true;
    }else{
        return false;
    }
}
int my_atoi ( const char * str ){
    // 1.jump over the whitespace character
    const char* p = str;
    while(is_whitespace(*p)){
        p++;
    }

    // 2. check plus or minus sign
    int sign = 1;
    if(*p=='-'){
        sign = -1;
        p++;
    }else if(*p=='+'){
        sign = 1;
        p++;
    }
    // 3.deal the number and ignore the other character
    int res = 0;
    while(*p){
        if(*p>='0'&&*p<='9'){
            res = res*10 + (*p - '0');  
        }
        p++;
    }

    return res*sign;
}
int main ()
{
  int i;
  char szInput [256];
  printf ("Enter a number: ");
  fgets ( szInput, 256, stdin );
  i = my_atoi(szInput);
  printf ("The value entered is %d. The double is %d.\n",i,i*2);
  return 0;
}

参考资料

  1. atoi
  2. itoa

PS

2012年写的文章


请我喝瓶饮料

微信支付码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注