编写整数字符串转化函数(不用itoa与atoi)

来源:互联网 发布:华为交换机端口应用acl 编辑:程序博客网 时间:2024/05/01 20:47

问题一:怎样将一个整数转化成字符串数,并且不用函数itoa

解析:整数转化成字符串,可以采用加‘0’,再逆序的办法,整数加‘0’就会隐性转化成char类型的数。

#include <iostream>
using namespace std;
#include <stdio.h>

int main()
{
  int num=12345,j=0,i=0;
  char temp[7],str[7];
 
  while(num)
  {
    temp[i]=num%10+'0';
    i++;
    num=num/10;
  }
  temp[i]=0;
  printf("temp=%s/n",temp);
  i=i-1;
  printf("temp=%d/n",i);

  while(i>=0)
  {
    str[j]=temp[i];
   j++;
   i--;
  }
  str[j]=0;
  printf("string=%s/n",str);
  return 0;
}

/*********************************************************************************************************************************

C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。以下是用itoa()函数将整数转 换为字符串的一个例子:

    # include <stdio.h>
    # include <stdlib.h>

    void main (void)
    {
    int num = 100;
    char str[25];
    itoa(num, str, 10);
    printf("The number ’num’ is %d and the string ’str’ is %s. /n" ,
    num, str);
    }

    itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制...