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,273
  • 3
  • 19
  • 41

3 Answers3

2
std::ostringstream os;
os << "C:/x/left" << i << ".bmp";
imagelist.push_back(os.str());
nosid
  • 47,164
  • 13
  • 106
  • 134
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
  • 45,192
  • 14
  • 103
  • 128
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
  • 83,021
  • 13
  • 171
  • 237