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 :)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

Related posts:

  1. Fetch Links From Twitter Into Your RSS Reader
  2. Tiny Bash Functions to Convert Between Numeric Representations
  3. Linux Fork Bomb Explained
  4. Brainfuck String Generator Generator
  5. Strip Leading Characters Off A String

Tags: ,

Friday, January 23rd, 2009 Programming

2 Comments to How to Convert a Number into a String in C++

  • How about lexical_cast from boost?

    string a = “x = ” + lexical_cast(x) ;

  • Amir Watad says:

    Yes I have to check out this Boost thing. I heard it has a great threads library as well.

  • Leave a Reply

    my email
    Already a member?
    Login
    Login using Facebook:
    Last visitors
    my photo
    Hi,
    My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and am currently studying for a BSc. in electrical engineering at The Electrical Engineering school , Technion , Israel.
    I work at the verification dept. in Mellanox Technologies Ltd.
    I love Linux, the Command Line and the OpenSource Community.
    I used to write Poems (Arabic) when I was able to find time for this.
    January 2009
    S M T W T F S
    « Dec   Feb »
     123
    45678910
    11121314151617
    18192021222324
    25262728293031
    Opensource Logo
    SEO Powered by Platinum SEO from Techblissonline

    Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.