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

Started by
5 comments, last by Googol PL3X 15 years, 8 months ago
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.
Advertisement
With std::stringstream:
// #include <sstream> at the top of your filestd::stringstream str;str << "Player" << attachedControlers;names.push_back(str.str());
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


Why did Doug Gregor create the empty directory?
Hey thanks guys, a few questions

Whats the boost namespace I've never heard it?

And what does lexical_cast do?
Quote:Original post by Googol PL3X
Hey thanks guys, a few questions

Whats the boost namespace I've never heard it?

And what does lexic_cast do?
Boost and lexical_cast.
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
Why did Doug Gregor create the empty directory?
Awsome, thanks mate :)

This topic is closed to new replies.

Advertisement