Re: [Dev-C++] itoa - atoi : another implementation
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-04-02 18:12:24
|
It takes less code - and is faster - to count needed buffer space and
insert backwards than to have to flip at the end.
One more thing. Why call j=3Dstrlen(s)-1 in the last loop, when you already
know how many characters you have inserted in the string?
/Per W
On Wed, 2 Apr 2003, Ricardo L=F3pez Ruiz wrote:
> 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=3Dn)<0) /* changing the sign of a negative number */
> n=3D-n;
>
> i=3D0; /* obtaining the digits of the number */
> do{
> s[i++]=3Dn%10 + '0';
> }while((n/=3D10)>0);
>
> if(sign<0) /* returning the correct sign */
> s[i++]=3D'-';
> s[i]=3D'\0'; /* end of the string */
>
> /* reverse (s) */
> for(i=3D0,j=3Dstrlen(s)-1 ;i<j ; i++,j--)
> {
> c=3Ds[i];
> s[i]=3Ds[j];
> s[j]=3Dc;
> }
>
> 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=3D0; /* tranforming s to a number n */
> for(i=3D0;s[i]>=3D'0' && s[i]<=3D'9'; ++i)
> n=3Dn*10+(s[i]-'0');
>
> printf("the number is: %ld\n number of digits: %d\n",n,i);
> printf("FIN\n");
> system("PAUSE");
> return 0;
> }
> ************************************
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: ValueWeb:
> Dedicated Hosting for just $79/mo with 500 GB of bandwidth!
> No other company gives more support or power for your dedicated server
> http://click.atdmt.com/AFF/go/sdnxxaff00300020aff/direct/01/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|