• Advertisement
Sign in to follow this  

long appended to string

This topic is 4522 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

How do i append a number to the end of a std::string? I'm trying to have an array of something but store it a different way: for (long i=0 ; i<10 ; i++ { string str = "Name" + i; myPrint(str.c_str()); } for some reason, i'm getting things like Name ame me e what's wrong? or can i not append numbers that way?

Share this post


Link to post
Share on other sites
Advertisement
#include <sstream>

for (int i = 0; i < 10; ++i)
{
std::stringstream sstr;
sstr << "Name" << i;
myPrint(sstr.str().c_str());
}
or
for (int i = 0; i < 10; ++i)
{
std::string str = "Name" + boost::lexical_cast< std::string >(i);
myPrint(str.c_str());
}
Enigma

Share this post


Link to post
Share on other sites
When you say string str = "Name" + i i doesn't automatically get converted to a string. Instead, some odd pointer addition goes on that I'll leave to someone smarter to explain.

So, to convert from a number to a string use a string stream or boost::lexical_cast. Then you can add it to the string using +/+=

EDIT: Beaten :0

Share this post


Link to post
Share on other sites
"Name" is a char*. The addition happens before the type coercion, so what happens is that you increment the pointer (so that it points into the middle of "Name", at progressively further points), and then construct a std::string using that pointer.

Meanwhile, std::string does define an operator+ overload, but only for char*'s and for other std::strings. To append the number you will need a std::stringstream (or a wrapper around that technique, e.g. boost::lexical_cast), as stated.

Share this post


Link to post
Share on other sites
I think it's:

std::stringstream sstr;
sstr.str(std::string());

But in the examples above you won't need to; it'll be destroyed and recreated on every iteration of the loop.

Share this post


Link to post
Share on other sites
If you clear the stringstream via the str() member function, you'll generally also want to clear the status bits on the stream as well. This is something you don't need to worry about if the stream is recreated as needed rather than kept around.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement