美文网首页
字符串和数字之间相互转换

字符串和数字之间相互转换

作者: 小码弟 | 来源:发表于2018-10-20 11:48 被阅读0次

自定义库函数:atoi和itoa

#include <iostream>
using namespace std;

int atoi(char* s)
{
    if(s == NULL)
    {
      cout<<"Invalid Input"<<endl;
      return -1;
    }
    while(*s == ' ') // 去掉开头空格
      s++;
    
    int sign = (*s == '-')?-1:1;
    if(*s == '-')s++; // 跳过符号位
    int result = 0;
    while(*s >= '0' && *s <= '9') 
    {
        result = result*10 + (*s - '0');
        s++;
    }
    while(*s == ' ') // 去掉末尾的空格
      s++;
    if(*s != '\0')
      {
        cout<<"Invalid Input"<<endl;
        return -1;
      }
    return result*sign;
}
/*---------------------------------------*/

char* itoa(int num, char* str, int base)
{
  char* ptr = str;
   int sign = num;
   if(sign < 0)
     num = -num;
  while(num)
  {
    *ptr++ = num%base + '0';
    num = num/base + '0';
    if(num < base)
    {
        *ptr++ = num + '0';
        break;
    }

  if(sign < 0) *ptr++ = '-';
  *ptr = '\0';

  int j  = ptr - str - 1; //获取转换后的字符数,不包含'\0'
  for(int i = 0; i<j;i++, j--) // 首尾互换
  {
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;
  }
  return str;
  }
}

相关文章

网友评论

      本文标题:字符串和数字之间相互转换

      本文链接:https://www.haomeiwen.com/subject/lwauzftx.html