Why C++ is a bad language: here’s how to convert floats and integers to a string

What do you do when a student asks you a valid question and you think your answer ought to be wrong but that’s the only answer you have? You turn it into a blog post!

How do you convert an integer to a string in C++? I mean, it is a pretty basic operation, right?

Here’s what I wish it was…

string s = "some text = ";
s.append(2);

Well no. The basic string object in C++ is just a container. The following code is the C++ way to to convert numbers to strings.

#include <sstream>
#include <iostream>
using namespace std;
int main() {
stringstream sstr;
int integer = 2;
float floater = 2.2f;
sstr < < "La vie est belle" << integer << floater << endl; string result = sstr.str(); const char * cresult = result.c_str(); cout << result << endl; return 0; }

Ok, I cheated a bit, but you get my point.

Published by

Daniel Lemire

A computer science professor at the Université du Québec (TELUQ).

5 thoughts on “Why C++ is a bad language: here’s how to convert floats and integers to a string”

  1. Or you do yourself a favour and install Boost, and then you just do:

    #incliude “boost/lexical_cast.hpp”
    #include

    using boost::lexical_cast;
    using std::string;

    string s = “some text = “;
    s += lexical_cast(your_float);

    (and lexical cast isn’t limited to that – it works to/from all numeric types and string)

    Which, the additional include and the optional using declaration aside is pretty close to what you wanted, with the difference that there’s no ambiguity about what you want to express.

    Vidar

  2. Oops. At my less than/greater than’s. The code example should be:

    #include “boost/lexical_cast.hpp”
    #include <string>

    using boost::lexical_cast;
    using std::string;

    string s = “some text = “;
    s += lexical_cast<string>(your_float);

  3. You are right Robin:

    We aim to establish “existing practice” and provide reference implementations so that Boost libraries are suitable for eventual standardization. Ten Boost libraries are already included in the C++ Standards Committee’s Library Technical Report (TR1) as a step toward becoming part of a future C++ Standard. More Boost libraries are proposed for the upcoming TR2.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax