[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppIntToStr

(C++) Converting an integer to a std::string

In analogy with the standard 'atoi' function, doing the other way around:

(function taken from from Marshall Cline's C++ FAQ Lite document http://www.parashift.com/c++-faq-lite/)

  1. include <sstream>
  2. include <cassert>
std::string itoa(const int x) { std::ostringstream o; if (!(o << x)) return "ERROR"; return o.str(); } int main() { assert(itoa(69)=="69"); }


You could also use the Boost C++ Library's lexical_cast:

  1. include <cassert>
  2. include <string>
  3. include <boost/lexical_cast.hpp>
int main() { const int i = 123; const std::string s = boost::lexical_cast<std::string>(i); assert(s == "123"); }


Other code snippets

(C++ Builder) Converting an integer to a String

Code links



last edited (June 13, 2007) by bilderbikkel, Number of views: 9555, Current Rev: 14 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.