andrea
andrea

Reputation: 1358

stringstream and for loop

I'm using a stringstream to generate "dynamically", the name of the files I need to open and this is my code:

for (int img=0; img<5; img++)
{
stringstream stream;
string *s=new string("myfile");
stream << img << ".png"
s->append(stream.str());

.. other code

the problem is than the first time the program flows into the loop it works fine, the second time stream does not has the value "1.png", but has value null... so when I try to open the file I get a null pointer.

ho do I fix this?

Upvotes: 1

Views: 2205

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477160

A simpler solution:

for (int img = 0; img < 5; ++img)
{
    std::string s = "myfile" + ('0' + img) + ".png";

    // do something useful with s
}

If numbers are bigger than 9, you can use std::to_string(img) instead.

Upvotes: 3

johnathan
johnathan

Reputation: 2355

Try allocating your string before your loop.

string *s = new string("myfile");

for(;;;){} //forloop // use s here.

delete s; // always delete dynamically allocated memory.

Upvotes: 1

Related Questions