我使用字符串流“动态”生成我需要打开的文件名,这是我的代码:
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…所以当我试图打开这个文件时,我得到一个空指针。
我该怎么解决这个问题?
发布于 2011-12-06 22:46:03
尝试在循环之前分配字符串。
string *s = new string("myfile");
for(;;;){} //forloop //此处使用%s。
delete s; //始终删除动态分配的内存。
发布于 2011-12-06 22:46:58
一个更简单的解决方案:
for (int img = 0; img < 5; ++img)
{
std::string s = "myfile" + ('0' + img) + ".png";
// do something useful with s
}如果数字大于9,则可以改用std::to_string(img)。
https://stackoverflow.com/questions/8401695
复制相似问题