stringstream and for loop

stringstream and for loop

本文关键字:loop for and stringstream      更新时间:2023-10-16

我使用stringstream来生成"动态",我需要打开的文件的名称,这是我的代码:

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

的问题是比第一次程序流入循环它工作得很好,第二个时间流没有值"1.png",但有值null…所以当我试图打开文件时,我得到一个空指针。

我怎么解决这个问题?

一个更简单的解决方案:

for (int img = 0; img < 5; ++img)
{
    std::string s = "myfile" + ('0' + img) + ".png";
    // do something useful with s
}

如果数字大于9,可以使用std::to_string(img)

尝试在循环之前分配字符串。

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

for(;;;){} //forloop //在这里使用s

delete s; //总是删除动态分配的内存