在 C++ 中将单反斜杠转换为双反斜杠
convert single back slash to double back slash in c++
>我有一条路径,例如"C:\home\my folder"。我想将其转换为"C:\\home\\my folder"。请建议我如何使用任何函数调用来执行此操作?
提前谢谢。
执行此操作的最佳方法是使用 Boost 字符串算法库。
http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo.html
使用以下命令:
std::string newPath = boost::replace_all_copy(testStr, "", "\");
这将导致替换和新形成的字符串。
希望这有帮助。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream lire("data.txt",ios::in);
string text ;
getline(lire,text); //text contains your repertory
cout<<text<<endl;
for (int i = 0 ; i < text.size();i++)
{
if(text[i] == '')
{
text.insert(i,"\") ;
i++;
}
}
cout<<text<<endl;
return 0;
}
以下程序对我有用。
#include <iostream>
#include <string>
#include <Shlobj.h>
int main()
{
std::string myPath;
std::cout << "Enter path to create: ";
std::cin >> myPath;
std::cout << "Path from user: " << myPath << "n";
::SHCreateDirectoryEx(nullptr, myPath.c_str(), nullptr);
return 0;
}
示例运行
如您所见,从用户输入中获取的路径仅使用单个反斜杠,但已成功创建目录。
Enter path to create: C:a_path
Path from user: C:a_path
我认为你追错了问题,假设你问这个问题的原因是因为你对SHCreateDirectoryEx
函数的调用失败了。
笔记:
- 当某些 Win32 API 函数失败(例如 CraeateDirectory)时,您必须调用
GetLastError
才能实际获取错误代码,但SHCreateDirectoryEx
并非如此(即,它直接返回失败代码)。 - 如果我使用正斜杠,
SHCreateDirectoryEx
函数也对我有用。
相关文章:
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 如何使用双黑斜杠从字符串中删除单反斜杠
- 如何将带有双反斜杠的字符串转换为单反斜杠
- 反斜杠和引号不计入字符串长度?
- 为什么Visual Studio正在清除我的一串反斜杠
- 在字符串 c++ 中将单反斜杠替换为双反斜杠
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 如何阻止反斜杠在从 QString 到 char 数组的转换中取消?
- 如何在 c++ 中读取与反斜杠分隔的键对应的值
- 有没有办法为 TAB 字符(反斜杠 t)"t"设置特定数量的最大空格数C++?
- 正则表达式括号表达式中的反斜杠
- 在带有转义反斜杠的窗口上打印加速路径
- 删除 std::string 上的反斜杠字符时出现问题
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- 如何从QString中删除反斜杠?
- 修改正则表达式以包含反斜杠和单引号(以便反斜杠表现为转义字符)
- 反斜杠导致问题 c++
- 在 C++ 中将单反斜杠转换为双反斜杠
- 将字符转换为字符串时,反斜杠消失
- 将反斜杠字符串转换为反斜杠字符