Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

std::wstring and Konsole from Kde

18 views
Skip to first unread message

Szyk Cech

unread,
Jun 2, 2019, 1:29:39 AM6/2/19
to
Hi
I wrote std::string to std::wstring helper functions. They basically
works, but std::wcout prints rubbish instead unicode characters. My
program is as follow:

#include <string>
#include <iostream>
#include <codecvt>
#include <locale>

std::wstring gToWide(const std::string& aNarrow)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> lConverter;
return lConverter.from_bytes(aNarrow);
}

std::string gToNarrow(const std::wstring aWide)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> lConverter;
return lConverter.to_bytes(aWide);
}

int main(/*int argc, char *argv[]*/)
{
std::string lStr1("zażółć gęślą jaźń");
std::wstring lStr2(gToWide(lStr1));

// std::cout << "sizeof(wchar_t): " << sizeof(wchar_t) << std::endl;
// std::cout << lStr1 << std::endl;
std::wcout << lStr2 << std::endl;
// std::cout << gToNarrow(lStr2) << std::endl;
return EXIT_SUCCESS;
}

Output is like this:
$ ./StringConversions
za???? g??l? ja??


But when main is like this:

int main(/*int argc, char *argv[]*/)
{
std::string lStr1("zażółć gęślą jaźń");
std::wstring lStr2(gToWide(lStr1));

std::cout << "sizeof(wchar_t): " << sizeof(wchar_t) << std::endl;
std::cout << lStr1 << std::endl;
std::wcout << lStr2 << std::endl;
std::cout << gToNarrow(lStr2) << std::endl;
return EXIT_SUCCESS;
}

Output changes to this:

$ ./StringConversions
sizeof(wchar_t): 4
zażółć gęślą jaźń
za|�B g[l jazD
zażółć gęślą jaźń

I suppose the second main() is improper due to (claimed in the past by
GNU developers) undefined bechaviour when mixing std::cout and std::wcout.

But first main() should work. But it does not. Please help me.

thanks and best regards
Szyk Cech

Ralf Goertz

unread,
Jun 2, 2019, 3:53:49 AM6/2/19
to
Am Sun, 2 Jun 2019 07:29:28 +0200
schrieb Szyk Cech <szyk...@spoko.pl>:
You need to desynchronize stdio and std::ios:

std::ios::sync_with_stdio(false);

and also imbue a utf8 locale to both cout and wcout:

std::cout.imbue(std::locale(""));
std::wcout.imbue(std::locale(""));

(This works here because std::locale("") gives the default locale in the
environment which happens to be de_DE.UTF-8 in my case.)

Doing so at the beginning of each version of main gives:

zażółć gęślą jaźń

and

sizeof(wchar_t): 4
zażółć gęślą jaźń
zażółć gęślą jaźń
zażółć gęślą jaźń

respectively.

0 new messages