【问题标题】:How to retain filesystem path while converting to string?转换为字符串时如何保留文件系统路径?
【发布时间】:2021-10-18 04:28:30
【问题描述】:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std;
int main()
{
    fs::path p = fs::current_path();

    cout << p << endl;
    string p_string = p.string();
    cout << p_string << endl;
    return 0;
}

当打印出 'p' 时,路径如下所示。

"C:\\Users\\tp\\source\\repos\\test"

但是在转换成字符串之后是这样的。

C:\Users\tp\source\repos\test

有没有办法可以保留路径的原始形式?

【问题讨论】:

    标签: c++ filesystems c++17


    【解决方案1】:

    来自cppreference's page on operator&lt;&lt;(std::filesystem::path)

    在路径 p 上执行流输入或输出。使用std::quoted 是为了让空格在以后被流输入操作符读取时不会导致截断。

    所以我们将通过手动调用std::quoted得到相同的字符串:

    #include <iostream>
    #include <iomanip>
    #include <filesystem>
    
    namespace fs = std::filesystem;
    using namespace std;
    
    int main()
    {
       fs::path p = fs::current_path();
    
       // Should be same
       cout << p << endl;
       cout << std::quoted(p.string());
    
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 2021-09-07
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多