How to Convert a Number into a String in C++
I found a few ways to convert a number into C++, some of them are C style (like using sprintf), and some are ugly (i.e non-standard, like using itoa), and there some nice way which uses string streams to achieve this.
Where going to define and implement a function called Stringify, which accepts an integer and returns a string (this can be extended to accept any numeric value).
Here is a C++ code, which implements this function, and uses it in a simple example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 #include <iostream>
#include <string>
#include <sstream>
using namespace std;
string
Stringify(int number) {
ostringstream tmpStr;
tmpStr << number;
return(tmpStr.str());
};
int
main() {
int x = 42;
string y = "x = " + Stringify(x);
cout << y << endl;
return(0);
}
Notice that we included iostream so we can use cout, and sstream so we can use string streams. We also need to include string since we’re dealing with strings.
Hope that this is useful for somebody
Related posts:
2 Comments to How to Convert a Number into a String in C++
Leave a Reply
About Me
Tags
My Twitter
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Science
- Security
- Shell Scripts
- Short Posts
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (2)

How about lexical_cast from boost?
string a = “x = ” + lexical_cast(x) ;
Yes I have to check out this Boost thing. I heard it has a great threads library as well.