The question is how to convert wstring to string?
I have next example :
#include
#include
int main()
{
std::wstr
There are two issues with the code:
The conversion in const std::string s( ws.begin(), ws.end() );
is not required to correctly map the wide characters to their narrow counterpart. Most likely, each wide character will just be typecast to char
.
The resolution to this problem is already given in the answer by kem and involves the narrow
function of the locale's ctype
facet.
You are writing output to both std::cout
and std::wcout
in the same program. Both cout
and wcout
are associated with the same stream (stdout
) and the results of using the same stream both as a byte-oriented stream (as cout
does) and a wide-oriented stream (as wcout
does) are not defined.
The best option is to avoid mixing narrow and wide output to the same (underlying) stream. For stdout
/cout
/wcout
, you can try switching the orientation of stdout
when switching between wide and narrow output (or vice versa):
#include
#include
#include
int main() {
std::cout << "narrow" << std::endl;
fwide(stdout, 1); // switch to wide
std::wcout << L"wide" << std::endl;
fwide(stdout, -1); // switch to narrow
std::cout << "narrow" << std::endl;
fwide(stdout, 1); // switch to wide
std::wcout << L"wide" << std::endl;
}