0

I'm trying to do something like this: Name[i] = "Name" + (i+1) in a forloop, so that the values of the array will be: Name[0] = Name1, Name[1] = Name2, Name[2] = Name3.

Is there an easier way to do this beside converting the value of i to a char and add it to the string?

Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
ylhtravis
  • 105
  • 1
  • 2
  • 10

2 Answers2

2

When using C++2011 you can also use std::to_string():

name[i] = "Name" + std::to_string(i + 1);

This should avoid the need to create a string stream.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • And if your compiler doesn't provide it yet, you can find several different implementations to choose from [here](http://stackoverflow.com/questions/4351371/c-performance-challenge-integer-to-stdstring-conversion) – Ben Voigt Feb 20 '12 at 00:25
1

That's what std::stringstream is for:

std::stringstream ss;
ss << "Name" << (i+1);

...

name[i] = ss.str();
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 2
    Is there any particular reason not to use `std::ostringstream`? (note the funny `o` after `std::`) – Dietmar Kühl Feb 20 '12 at 00:10
  • @DietmarKühl: Any particular reason *to* use it? – Oliver Charlesworth Feb 20 '12 at 00:11
  • The object is simpler and somewhat faster to construct although `std::istream` doesn't really add any members. Since the open mode is passed to the `std::stringbuf` this class can avoid some set up if it knows that it will only be used for input or output (although most implementations ignore this). Finally, it states what the stream is actually used for (well, I managed to use `i` when I mean `o`). – Dietmar Kühl Feb 20 '12 at 00:16
  • @DietmarKühl: The only reason I can think of is that [it's slower than molasses](http://stackoverflow.com/questions/4351371/c-performance-challenge-integer-to-stdstring-conversion). Hopefully this isn't a big enough chunk of the overall program to matter. – Ben Voigt Feb 20 '12 at 00:17
  • Thank you so much for your help. It worked! I'm not that familiar with stringstream. I will learn more about it. – ylhtravis Feb 20 '12 at 00:19