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;
}

When printing out ‘p’ the path is shown as this.

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

But after the conversion to a string it comes out like this.

C:Userstpsourcerepostest

Is there a way I could retain the original form of the path?

Answer

From 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.

So we’ll get the same string by manually calling 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;
}