【发布时间】:2014-12-06 17:33:53
【问题描述】:
我正在尝试使用 .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一次,将结果存储在变量中,然后操作该变量。 -
@parameter 查看我的答案。