我正在尝试使用 .replace 命令创建用 .txt 替换目录中的 .png 和 .jpg 文件(其中的所有文件仅包含这些扩展名)的字符串,如下所示:
//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
最佳答案
如果要替换最后三个字符,则需要提供包含三个字符的范围。目前,您的范围只有两个字符,即从 end()-3
(含)到 end()-1
(不包括) .
string s("hello.png");
s.replace(s.end()-3, s.end(), "txt");
cout << s << endl;
此外,需要确保字符串的长度不少于三个字符,否则访问end()-3
是未定义的行为。
此外,请确保您没有多次使用 dir.getPath(i)
,否则您的 end()-3
迭代器和 end()
迭代器指向不同的字符串。即
string b = dir.getPath(i).replace(dir.getPath(i).end()-3, dir.getPath(i).end(), "txt"); // Crashes
// ^^^^^^ ^^^^^^ ^^^^^^^
// Copy # 1 Copy # 2 Copy # 3
需要
string b = dir.getPath(i);
b.replace(b.end()-3, b.end(), "txt"); // Does not crash
关于c++ - 替换文件扩展名时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26318201/