[LC++]strings and numbers

Jack Lloyd lloyd at acm.jhu.edu
Thu Jul 4 02:25:07 UTC 2002


On Wed, 3 Jul 2002, Vincent Penquerc'h wrote:

> > I'm getting a little tired of using atoi and sprintf to
> > convert between
> > numbers and strings. I'm using STL strings, and I was thinking that
> > perhaps it have some build in methods that can do the trick smothly?
>
> In case it doesn't exist (it sure does however :)), you can
> factor code:
>

Here's a little something I use a lot, particularly when I'm throwing an
exception becuase someone gave a bad argument to a function, ie:

throw someexception("Bad user: " + to_string(somearg) + " is way too big");

std::string to_string(u64bit n)
   {
   if(n)
      {
      std::string lenstr;
      while(n > 0)
         {
         lenstr = (char)('0' + n % 10) + lenstr;
         n /= 10;
         }
      return lenstr;
      }
   else
      return "zero";
   }

Probably the best all-around solution is to use the string stream types
inside a function like the one above. The reason I'm not doing so is the
code has to support older compilers (egcs 1.1.2, various commercial things)
that don't have the ISO string streams.

-Jack





More information about the tuxCPProgramming mailing list