2

What I want to do is this:

int num = 10;
string message = "something something " + num;
cout<<message<<endl;

the output would be:  something something 10

The compiler I'm being forced to use is an outdated version of GCC, and does not have C++ 11 support, which means to_string will not work.

Is string stream the only way? If so, how would I use it in this case to produce the least amount of code?

3
  • 3
    just use cout<<message<<num<<endl; in this case? And yes, stringstream is probably the easiest general solution, others exist tho. Commented Apr 1, 2014 at 1:44
  • @RaphaelMiedl this isn't an exact example. In reality, I want to return message to a caller function, however string stream seems to be the way to go. Commented Apr 1, 2014 at 1:50
  • boost::lexical_cast will do this almost just as easily. Commented Apr 1, 2014 at 1:54

1 Answer 1

3

You can write your own to_string:

template <typename T>
inline std::string to_string(const T& t)
{
    std::ostringstream oss;
    oss << t;
    return oss.str();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.