C++ Concatenate a String with an int

Posted On December 25, 2007

Filed under C/C++
Tags: , , , ,

Comments Dropped 3 responses

Recently I had a very simple problem in C++ – I had to enumerate 5 filenames with an index in their name: stars1.jpg, …, stars4.jpg

Apparently it is not as easy as it sounds. If it were only strings that I was concatenating, then I could just use the ‘+’ operator and it would work, but the operator is not defined for int’s – I found a possible solution, which uses a stream to concatenate elements of different types into a single string.

#include <string>
#include <iostream>
#include <sstream>

// ............

  for (int i = 0; i < 4; i++) {
    std::ostringstream o;
    o << "stars" << i + 1 << ".jpg";
    std::cout << o.str() << std::endl;
  }

// ............

The important thing to note here is that the stream is created from scratch each time we are composing a new filename. I could not find a way to clear a stream and thinking about it now I see that if there would be such a way the design of the stream would be wrong. So I am creating a new one each time.If you can find a better way of doing this, please tell me.Based on: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1