我有大约 3500 个完整文件路径需要排序(ex. "C:\Users\Nick\Documents\ReadIns\NC_000852.gbk")。我刚刚了解到,C++ 在读取文件路径时无法识别单个反斜杠。我正在读取大约 3500 个文件路径,因此手动更改每个路径会非常繁琐。
我有一个for循环,它找到单个反斜杠并在该索引处插入一个双反斜杠。这:
string line = "C:\Users\Nick\Documents\ReadIns\NC_000852.gbk";
for (unsigned int i = 0; i < filepath.size(); i++) {
if(filepath[i] == '\') {
filepath.insert(i, '\');
}
}
Run Code Online (Sandbox Code Playgroud)
然而,c++,特别是 c::b,由于反斜杠字符而无法编译。有没有办法用函数添加额外的反斜杠字符?
我正在从文本文件中读取文件路径,因此它们被读入string filepath变量中,这只是一个测试。
使用双反斜杠作为'\\'和"C:\\Users..."。因为单个反斜杠与下一个字符会进行转义。
此外,该string::insert()方法的第二个参数需要字符数,而您的代码中缺少该字符数。
通过所有这些修复,它可以正常编译:
string filepath = "C:\\Users\\Nick\\Documents\\ReadIns\\NC_000852.gbk";
// ^^ ^^ ^^ ^^ ^^
for (unsigned int i = 0; i < filepath.size(); i++) {
if(filepath[i] == '\\') {
// ^^
filepath.insert(i, 1, '\\');
} // ^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)
我不确定上述逻辑将如何运作。但以下是我的首选方式:
for(auto pos = filepath.find('\\'); pos != string::npos; pos = filepath.find('\\', ++pos))
filepath.insert(++pos, 1, '\\');
Run Code Online (Sandbox Code Playgroud)
如果您只有单个字符需要替换(例如linux系统或可能在windows中支持);然后,您还可以使用此答案std::replace()中提到的方法来避免循环:
std::replace(filepath.begin(), filepath.end(), '\\', '/');
Run Code Online (Sandbox Code Playgroud)
我假设您已经创建了一个包含单个反斜杠的文件,并且您正在使用它进行解析。
但从您的评论中,我注意到显然您是在运行时直接获取文件路径(即在运行 .exe 时)。在这种情况下,正如 @MSalters 所提到的,您不必担心此类转换(即更改反斜杠)。