From cppreference.com
template<classCharT,classTraits=std::char_traits<CharT>,classAlloc=std::allocator<CharT>>std::basic_string<CharT,Traits,Alloc>string(constAlloc&a=Alloc())const; (1) (since C++17)std::stringstring()const; (2) (since C++17)std::wstringwstring()const; (3) (since C++17)std::u16stringu16string()const; (4) (since C++17)std::u32stringu32string()const; (5) (since C++17)std::stringu8string()const; (6)(since C++17)
(until C++20)std::u8stringu8string()const;(since C++20)Returns the internal pathname in native pathname format, converted to specific string type. Conversion, if any, is performed as follows:
If path::value_type is char, conversion, if any, is system-dependent. This is the case on typical POSIX systems (such as Linux), where native encoding is UTF-8 and string() performs no conversion.
Otherwise, if path::value_type is wchar_t, conversion, if any, is unspecified. This is the case on Windows, where wchar_t is 16 bit and the native encoding is UTF-16.
Otherwise, if path::value_type is char16_t, native encoding is UTF-16 and the conversion method is unspecified.
Otherwise, if path::value_type is char32_t, native encoding is UTF-32 and the conversion method is unspecified.
Otherwise, if path::value_type is char8_t, native encoding is UTF-8 and the conversion method is unspecified.
1) All memory allocations are performed by a.
6) The result encoding in the case of u8string() is always UTF-8.
Return value
The internal pathname in native pathname format, converted to specified string type.
Exceptions
May throw implementation-defined exceptions.
Example
Run this code
#include<clocale>#include<cstdio>#include<filesystem>#include<fstream>#include<iostream>#include<locale>intmain(){constchar*constlocaleName="ja_JP.utf-8";std::setlocale(LC_ALL,localeName);std::locale::global(std::locale(localeName));conststd::filesystem::pathp(u8"要らない.txt");std::ofstream(p)<<"File contents";// native string representation can be used with OS APIsif(std::FILE*constf=std::fopen(p.string().c_str(),"r")){for(intch;(ch=std::fgetc(f))!=EOF;)std::putchar(ch);std::fclose(f);}// multibyte and wide representation can be used for outputstd::cout<<"\nFile name in narrow multibyte encoding: "<<p.string()<<'\n';// wstring() will throw in stdlibc++ (as per gcc-12.1.0), see:// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95048// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102839// works with more recent gcc-12.2.1 (2023/02/01) and clang-10+std::wcout<<"File name in wide encoding: "<<p.wstring()<<'\n';std::filesystem::remove(p);}Possible output:
File contents File name in narrow multibyte encoding: 要らない.txt File name in wide encoding: 要らない.txt See also