转换为字符串时如何保留文件系统路径?

How to retain filesystem path while converting to string?

#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

有什么方法可以保留路径的原始形式吗?

来自cppreference's page on operator<<(std::filesystem::path)

Performs stream input or output on the path p. std::quoted is used so that spaces do not cause truncation when later read by stream input operator.

所以我们将通过手动调用 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;
}