Sign in to follow this  
Googol PL3X

How can I append a number at the end of a string object?

Recommended Posts

Googol PL3X    100
So far I've got this u32 attachedControlers = getNumberOfControls(); //vector to hold player names vector<string> names; if (attachedControlers > 1 && multiPlayer(attachedControlers)) for (int i = 0; i < attachedControlers; ++ i) { names.push_back("Player"); } else names.push_back("Player1"); But what I need is something that adds a number to the end based on what i is equal too, so if attachedControlers == 3 I will fill my vector with "Player1", "Player2" and "Player3", but I don't know how to append a number to the end without using c style strings.

Share this post


Link to post
Share on other sites
Evil Steve    2017
With std::stringstream:

// #include <sstream> at the top of your file

std::stringstream str;
str << "Player" << attachedControlers;
names.push_back(str.str());

Share this post


Link to post
Share on other sites
jochen    333
You can use std::ostringstream.


std::string Playername = "Player";
std::ostringstream StrStream;
StrStream << i;
Playername.append( StrStream.str() );



also to make it a little more readable, and if you are not afraid of using boost, you could write


std::string Playername = "Player";
Playername += boost::lexical_cast< std::string > ( i );




best Jochen


Share this post


Link to post
Share on other sites

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