int to string conversion

Stephen Webb stephen.webb at cybersafe.com
Tue Feb 15 19:15:48 GMT 2000


On Sat, 12 Feb 2000, Tobias Erbsland wrote:
> > Jerry L Kreps wrote:
> > > Martin Wiebusch wrote:
> > > > i was just wondering whether there is a function to convert integer
> > > > values to strings in any of the libaries. I already tried itoa, Itoa and
> > > > IntToStr. I also noticed there ist an Itoa function defined in the
> > > > Integer.h header. But I don't really need an Integer class, just a
> > > > little function to convert usual int variables into strings.
> > > You can use I/O manipulators (page 259, Practical C++
> > > programming)
> > Thankx, but I knew that Numbers are converted to strings when you write
> > them on stdout with cout << ...
> > What I want to do is writing that what in your examples appears on the
> > screen to a variable of the type "string".
> > Tilo Riemer just wrote me, that I can use "sprintf". But then I have to
> > guess how many digits number will have. So it would be great if there
> > was something like "sprintf" for instances of the string class. Any
> > idea?
> 
> Only a hint: Don't use the "strstream" class of the gcc package. You will
> get strange errors. But this class should be the solution of your problem:
> 
> int x = 23878979;
> strstram newnumber;
> 
> newnumber << x;
> 
> string test = "the new number is: " + newnumber.str();


If you want to use C++ (sprintf() is C, not C++), use a stringstrea.  It's
defined in the standard.

#include <sstream>
#include <string>

string intToString(const int anInt)
{
	ostringstream os;
	os << anInt;
	return os.str();
}

This function would work like the nefarious (and certainly non-standard)
itoa().  You can, of course, apply your favorite manipulators.

This works for me, but if you are using a non-conforming implementation of the
C++ standard library, you may have more difficulties.

SMW




More information about the KDevelop mailing list