如何在c++中向路径字符串添加反斜杠,以便ifstream函数正常工作而不会出现任何错误



在我的C++脚本中,我正在收集一个文件的路径,并将其存储在字符串中。

我想通过ifstream处理路径文件,但路径只有一个反斜杠,例如:

pathdir1dir2file.cfg

我需要转换此路径,添加另一个反斜杠,以便它在ifstream中工作,例如

path\dir1\dir2\file.cfg

如何让我的C++脚本以这种方式进行转换?

编辑

这个

string path = "pathdir1dir2file.cfg";
ifstream DirLuaExec(path);

导致此错误:

||=== Build: Debug in BatchParamCollect (compiler: GNU GCC Compiler) ===|
main.cpp||In function 'int main()':|
main.cpp|19|error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)'|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|495|note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|495|note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*'|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|481|note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char; _Traits = std::char_traits<char>]|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|481|note:   candidate expects 0 arguments, 1 provided|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|455|note: candidate: std::basic_ifstream<char>::basic_ifstream(const std::basic_ifstream<char>&)|
C:Program Files (x86)CodeBlocksTDM-GCC-64libgccx86_64-w64-mingw325.1.0includec++fstream|455|note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const std::basic_ifstream<char>&'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in BatchParamCollect (compiler: GNU GCC Compiler) ===|
||=== Run: Debug in BatchParamCollect (compiler: GNU GCC Compiler) ===|

但是这个:

string path = "path\dir1\dir2\file.cfg";
ifstream DirExec(path);

这非常有效,这就是为什么我需要双反斜杠!!!

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string path = "path\dir1\dir2\file.cfg";
string new_path = "";
for(int i = 0; i < path.size(); i++)
{
if(path[i] == '\')
{
new_path += path[i];   
new_path += path[i];   
}
else
{
new_path += path[i];     
}
}

cout << "Old path = " << path << endl; // This prints out pathdir1dir2file.cfg
cout << "New path = " << new_path << endl; // This prints out path\dir1\dir2\file.cfg
}

编译器只在编译时读取字符串,在这种情况下,您需要两个,因为第一个反斜杠将是转义符。因此,如果你想在代码中有一个静态路径字符串,你就必须这样做:

使用字符串文字可以避免在字符串中添加\的问题。它可与c++11一起使用。

#include<iostream>
#include<fstream>
#include<string>
int main () 
{
std::string path {R"(pathdir1dir2file.cfg)"};
std::ifstream  DirLuaExec(path);
}

最新更新