Sign in to follow this  

add an int to a string

This topic is 4243 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a function that takes a string, and i need to pass it a string that has an unsigned int in the middle of it. so if unsigned value was 3, i would need to make the string: "the value of the number is (3)" Thanks to anyone that can help me with this.

Share this post


Link to post
Share on other sites
Boost:

std::string s = "the value of the number is " + boost::lexical_cast<std::string>(3);

STL:

#include <sstream>

std::ostringstream sstr;
sstr << "the value of the number is ";
sstr << 3;

std::string s = sstr.str();

Or you could go an mostly C route:

char str[100];

sprintf(str, "the value of the number is %d", 3);

std::string s = str;

Share this post


Link to post
Share on other sites
If you're using C, you can use snprintf() which is just like printf but it writes into a string.

If you're using C++ you can use a stringstream like so.


#include <sstream>

std::ostringstream ouputString;

outputString << "the value of the number is (" << 3 << ")";

// call your function
func( outputString.str() );

Share this post


Link to post
Share on other sites

This topic is 4243 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this