# 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 on other sites
Evil Steve    2017
With std::stringstream:
// #include <sstream> at the top of your filestd::stringstream str;str << "Player" << attachedControlers;names.push_back(str.str());

##### 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 on other sites
Googol PL3X    100
Hey thanks guys, a few questions

Whats the boost namespace I've never heard it?

And what does lexical_cast do?

##### Share on other sites
Evil Steve    2017
Quote:
 Original post by Googol PL3XHey thanks guys, a few questionsWhats the boost namespace I've never heard it?And what does lexic_cast do?
Boost and lexical_cast.

##### Share on other sites
jochen    333
boost is a well known and imho very usefull resource for C++ developers.
You can find out about boost at www.boost.org.

boost::lexical_cast is a library that's part of boost.

Best Jochen

##### Share on other sites
Googol PL3X    100
Awsome, thanks mate :)