Any convenient ways of converting ints to strings?

Started by
15 comments, last by marijnh 19 years, 7 months ago
Are there any convenient ways of converting ints to strings? Without having to do huge if ladders or alike.
Advertisement
Boost lexical_cast, or for a basic mockup of what it does:
template<typename R, typename T>R lexical_cast(const T& t) {  R ret;  std::stringstream st;  if(!(st<<t) || !(st>>ret))    throw std::bad_cast();  return ret;}//usage:std::string s = lexical_cast<std::string>(10);

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

The way I do it:
inline std::string IntToString(int nNumber){char szBuff[32];   sprintf(szBuff,"%d",nNumber);   return szBuff;}
Thanks, after reading the resource page I went for a similar approach than that of Evil Steves'. :)
I normally use itoa, but after seeing the way you do it Evil Steve, I think I'm going to change my ways ;-)
What are the params for it though?

Edit: Do you have a link that tells me how to use this fully? I've had a look on msdn, and it's confusing and not very helpful (doesn't give a list of possible params)
____________________________________________________________Programmers Resource Central
eh, I'm not sure what you're asking Tera, but the Evil's function is ready for usage.

ex.
int month = 10;
string tempmonth;
tempmonth = IntToString(month);
Ok, maybe I didn't word that well.
What I wanted to know was what does the "%d" mean? And what other flags are there?
____________________________________________________________Programmers Resource Central
void int2string(int n, std::string &str){    do    {        int d = n % 10;        n = n / 10;        str += '0' + d;    } while(n != 0);}

That should do it.
Quote:Original post by Tera_Dragon
Ok, maybe I didn't word that well.
What I wanted to know was what does the "%d" mean? And what other flags are there?


%d - insert int
%f - insert float
%x - insert int in hex form
%s - insert string

there are some more but i cant remember them
%d reads a decimal integer
%i reads an integer
%c reads a char
%f reads a float
%s reads a string
%u reads an unsigned int
etc.

You should find the rest of the flags easily by searching for sprintf reference.

edit: damn mike, was just typing. ;P

This topic is closed to new replies.

Advertisement