As i have written Atoi(); Now i have written Itoa.
Here I have used a method of getting the last digit stroring it in an array and then reversing the array to get the required answer.
I look forward for Improvements in this code.
/****************************************************************************
Function Name:: itoa(int ,char [] )
Written By:: Susheel Kumar
Date:: Saturday 02 May 2009
----------------------------------------------------
Objective:: Convert an Integer to a cstring.
----------------------------------------------------
========================
Input Values::
Arg1 :: int (The Integer Needed To Be Converted)
Arg2 :: char [] (A space for holding the cstring)
--------------
Returning Value::
Pointer to cstring;
--------------
=========================
Known Flaws::
Unknown Response to shortage in cstring space ;
I.e.:
char b[2];
itoa(54321,b);//This size difference isnt defined.
****************************************************************************/
#include <iostream>
#include <cstring>
char* itoa(int a, char b[]); //Target Function;
//Functions Declarations
char get_char(int digit); //Converter from digit ie 0123456789 to char '0'......'9'
void rev(char *); //reverse function ;
//Functions
int main() //Example Program
{
char b[10];
char* string=itoa(543215,b);
std::cout<<"string:: "<<string<<" B== "<<b<<"\n";
}
char* itoa(int number, char strrep[])
{
int count=0;
while(number!=0)
{
int dig=number%10;
number-=dig;
number/=10;
strrep[count]=get_char(dig);
count++;
}
strrep[count]=0;
rev(strrep);
return strrep;
}
char get_char(int digit)
{
char charstr[]="0123456789";
return charstr[digit];
}
void rev(char *p)
{
char *q=&p[strlen(p)-1];
char *r=p;
while(q>r)
{
char s=*q;
*q=*r;
*r=s;
q--;
r++;
}
}