4WebHelp
 FAQ  •  Search  •  User Groups  •  Forum Admins  •  Smilies List  •  Statistics  •  Rules   •  Login   •  Register
Toggle Navigation Menu

 Converting a number to a string
Post New TopicReply to Topic
View Previous Topic Print this topic View Next Topic
Author Message
kepler
Junior WebHelper
Junior WebHelper


Joined: 08 Feb 2002
Posts: 37

PostPosted: Thu Oct 07, 2004 3:07 pm (19 years, 6 months ago) Reply with QuoteBack to Top

Hi,

Does anyone knows, in C, what function must we use to convert a number to a string?

Regards,

Kepler
OfflineView User's ProfileFind all posts by keplerSend Personal Message
adam
Forum Moderator & Developer



Joined: 26 Jul 2002
Posts: 704
Location: UK

PostPosted: Thu Oct 07, 2004 3:46 pm (19 years, 6 months ago) Reply with QuoteBack to Top

I don't think there is one in the standard library, but this example from the C book will do it:
Code:
#include <string.h>

void reverse(char s[])
{
   int c,i,j;

   for(i=0, j = strlen(s)-1; i < j; i++, j--) {
      c = s[i];
      s[i] = s[j];
      s[j] = c;
   }
}

void itoa(int n, char s[])
{
   int i, sign;

   if ((sign = n) < 0)   /* record sign */
      n = -n;          /* make n positive */
   i = 0;
   do {    /* generate digits in reverse order */
      s[i++] = n % 10 + '0';   /* get next digit */
   } while ((n /= 10) > 0);
   if (sign < 0)
      s[i++] = '-';
   s[i] = '\0';
   reverse(s);
}


Just call atoi with the number and the char array you want it stored in. If it doesn't compile, it's probably because I typed it wrong Wink

________________________________
It's turtles all the way down...
OfflineView User's ProfileFind all posts by adamSend Personal MessageVisit Poster's Website
Display posts from previous:      
Post New TopicReply to Topic
View Previous Topic Print this topic View Next Topic


 Jump to:   




You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot edit your posts in this forum.
You cannot delete your posts in this forum.
You cannot vote in polls in this forum.


Page generation time: 0.210675 seconds :: 18 queries executed :: All Times are GMT
Powered by phpBB 2.0 © 2001, 2002 phpBB Group :: Based on an FI Theme