C++ Concatenate a String with an int

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.


// …………

for (int i = 0; i < 4; i++) { std::ostringstream o; o << "stars" << i + 1 << ".jpg"; std::cout << o.str() << std::endl; } // ............ [/sourcecode] 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


3 thoughts on “C++ Concatenate a String with an int

  1. Mike says:

    This is an old post, I realize, but probably one that gets looked at a lot based on how high it is on google for a fairly common search. Another option is to deal with chars instead of ints, since you can concatenate strings and chars directly:

    string s = “stars”;
    for (int i=1; i <= 4; i++)
    cout << s + (char)(i+48) << endl; //ASCII value of ‘0’ is 48, so value of ‘n’ is 48 + n, n < 10

  2. Mike says:

    Or, probably the simplest of ways:

    for (int i=1; i <= 4; i++)
    cout << “stars” << i << “.jpg” << endl;

    and of course above, I meant:
    cout << s + (char)(i+48) + “.jpg” << endl;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s