Convert number to a string

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
Slopey
Posts: 24
Joined: Sun Jul 31, 2005 8:13 pm

Convert number to a string

Post by Slopey »

Hi All,

What's the easiest way to convert a number to a string (for example an integer?) in C/C++?

In the past Ive used itoa but I believe thats non-standard.

Thanks in advance - it's been a while since I've done any C/C++ and this one has complete escaped me - it's also missing from my books :/

Cheers,
S.
User avatar
Raphael
Posts: 646
Joined: Tue Jan 17, 2006 4:54 pm
Location: Germany
Contact:

Post by Raphael »

Either use itoa as you said, or do the dirty way with sprintf.

Code: Select all

int i = 5023;
char number[32];
snprintf(number,32,"%i",i);
ADePSP
Posts: 58
Joined: Thu Jul 13, 2006 9:07 pm

Post by ADePSP »

Raphael wrote:Either use itoa as you said, or do the dirty way with sprintf.

Code: Select all

int i = 5023;
char number[32];
snprintf(number,32,"%i",i);
Why is "sprintf" dirty...? Really, i'm new and I use this...?

Code: Select all

  char buffer[200];
  float num = 20.39999999;

  sprintf(buffer,"Why is this wrong...? Does this float look nice %.02...?",num);
If there is something wrong with that please tell us...?

ADe

P.S. Apart from declaring more bytes for the char than were needed... :D
User avatar
Raphael
Posts: 646
Joined: Tue Jan 17, 2006 4:54 pm
Location: Germany
Contact:

Post by Raphael »

ADePSP wrote: Why is "sprintf" dirty...? Really, i'm new and I use this...?
Well, it's not really dirty, I just called it that in this case, as it needs the extra line to declare your buffer ;)
ADePSP wrote:

Code: Select all

  char buffer[200];
  float num = 20.39999999;

  sprintf(buffer,"Why is this wrong...? Does this float look nice %.02...?",num);
If there is something wrong with that please tell us...?
well, I think it should be %.02f but other than that it's perfectly fine
Post Reply