Re: [Dev-C++] itoa - atoi : another implementation
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ricardo R. <ri...@po...> - 2003-04-02 11:23:38
|
If you are interested in another implementation
of itoa( ) and atoi ( ), here you have the code.
Hope it can be helpful.
Ricardo.
**************ITOA( ) ******************
/* ITOA: Transforms the long n to a string s */
#include <stdio.h>
#include <string.h>
main( )
{
char s[500];
long int n,sign;
int i,j,c;
printf("give me a number to convert:\n");
scanf("%ld",&n);
if((sign=n)<0) /* changing the sign of a negative number */
n=-n;
i=0; /* obtaining the digits of the number */
do{
s[i++]=n%10 + '0';
}while((n/=10)>0);
if(sign<0) /* returning the correct sign */
s[i++]='-';
s[i]='\0'; /* end of the string */
/* reverse (s) */
for(i=0,j=strlen(s)-1 ;i<j ; i++,j--)
{
c=s[i];
s[i]=s[j];
s[j]=c;
}
printf("the result is:\n%s\n",s);
printf("FIN\n");
system("PAUSE");
return 0;
}
************************************
***************** ATOI( ) ***************
/* ATOI: Reading a number as a string s and returning it as a number n */
#include <stdio.h>
main( )
{
char s[100];
long int n; int i;
printf("give a number chain: \n");
gets(s);
printf("your number chain is: %s\n",s);
n=0; /* tranforming s to a number n */
for(i=0;s[i]>='0' && s[i]<='9'; ++i)
n=n*10+(s[i]-'0');
printf("the number is: %ld\n number of digits: %d\n",n,i);
printf("FIN\n");
system("PAUSE");
return 0;
}
************************************
|