Index:
[thread]
[date]
[subject]
[author]
From: Robert C. Duvall <rcd@cs.duke.edu>
To :
Date: 15 Feb 1999 17:58:46 -0500
Re: itoa
> > Is it defined in the g++ library? If yes, then how to use it (I tried the
> > man pages, nothing exists for itoa). If no, then is there a function to
> > convert integer to string?
>
> To convert an int to a string, use the function sprintf. For example,
> if num is a int in your program:
>
> string numStr;
> sprintf(numStr.c_str(), "%d", num);
I sit corrected. In C++, a better way to convert an int to a string
is to use an ostrstream. So, a better way to do the example above is:
ostrstream ost;
ost << num;
string str = ost.str();
This is better for at least one reason, it allows for standard stream
formatting:
ostrstream ost;
ost << setw(4) << num;
string str = ost.str();
Hope this helps,
rcd
Quick quiz for wednesday: explain a more fundamental reason as to why
the first example is grossly wrong.
--
Robert C. Duvall
Lecturer, Duke University
rcd@cs.duke.edu
Index:
[thread]
[date]
[subject]
[author]