我试图创建字符串,使用.replace命令替换我的.png和.jpg文件(其中的所有文件只包含这些扩展名).txt,如下所示:更换文件扩展名时崩溃
//say path is directory
path.replace(path.end()-3, path.end()-1, "txt");
它不断崩溃我的程序,但我做错了什么?它正确地找到'png'部分,但替换不起作用。
这里是我这样做的时候会发生什么。
string a = dir.getPath(i); //this is ..\data\images\Test0.png
string b = dir.getPath(i).replace(dir.getPath(i).end()-3, dir.getPath(i).end(), "txt"); //crashes
我敢打赌'dir.getPath(i)'每次调用时都会返回一个新的字符串。因此'dir.getPath(i).end() - 3'和'dir.getPath(i).end()'是两个迭代器到不同的*字符串中,这两个字符串都不是你调用'replace'的那个。相反,执行'a.replace(a.end()...)' - 调用'getPath'一次,将结果存储在一个变量中,然后处理该变量。 – 2014-10-11 19:21:51
@parameter查看我的回答。 – 2014-10-11 19:35:25