0

Possible Duplicate:
Easiest way to convert int to string in C++

I have a question about Visual C++ Strings. I want to concatenate the next string.

for (int i=0; i<23; i++)
{
    imagelist.push_back("C:/x/left"+i+".bmp");
    imagelist.push_back("C:/x/right"+i+".bmp");
}

Thx

Community
  • 1
  • 1
user558126
  • 1,303
  • 3
  • 21
  • 42

3 Answers3

2
std::ostringstream os;
os << "C:/x/left" << i << ".bmp";
imagelist.push_back(os.str());
nosid
  • 48,932
  • 13
  • 112
  • 139
2

One solution is to use stringstreams:

#include<sstream>

for (int i=0; i<23; i++)
{
    stringstream left, right;
    left << "C:/x/left" << i << ".bmp";
    right << "C:/x/left" << i << ".bmp";
    imagelist.push_back(left.str());
    imagelist.push_back(right.str());
}

stringstream is not the faster in performance solution, but is easy to understand and very flexible.

Another option is to use itoa and sprintf, if you feel at home with c style printing. However, I have heard that itoa is not very portable function.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
2
for (int i=0; i<23; i++)
{
    imagelist.push_back("C:/x/left"+std::to_string(i)+".bmp");
    imagelist.push_back("C:/x/right"+std::to_string(i)+".bmp");
}
bames53
  • 86,085
  • 15
  • 179
  • 244