在 C++ 中将单反斜杠转换为双反斜杠

convert single back slash to double back slash in c++

本文关键字:转换 单反斜 C++      更新时间:2023-10-16

>我有一条路径,例如"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函数也对我有用。