Re: std::cout << Glib::ustring(utf8_literal) throws exception



On Sun, 13 Jul 2008 20:14:55 -0700
Sohail Somani <sohail taggedtype net> wrote:
> Indeed, I believe I will have to use wcout after converting to UTF-16
> on Windows. But now the question is: what do I do to write portable
> code? On Linux, simply std::cout << Glib::ustring(some_utf8_string)
> works just fine.
> 
> I am wrapping Glib::ustring in my own string class so maybe the
> answer is to always use wcout and overload operator<< for that class
> for wostreams. This sounds very bad to me though.

I do not know enough about windows to know what you should do to
provide portable code.

If you are using gettext() to provide translated text for different
locales and it works with Windows, then you can set the output codeset
with bind_textdomain_codeset() so as to output UTF-8 (which you will
need to do anyway for GTK+ widgets), and if the windows console will
handle UTF-8 then you are home and dry.  If you do not call
bind_textdomain_codeset() then gettext() will output text in the
current locale's narrow codeset which may also work fine.

If you are not using gettext() then you can use printf() with wide
character string literals and the %ls format specifier.  printf("%ls",
L"überfällt") is guaranteed to provide the correct encoding for the
current locale's narrow codeset, provided the characters concerned exist
in that codeset, and is the most portable and non-OS dependent way of
providing non-ASCII text in narrow codeset form.

If however you intend to output string literals directly and
printf()/snprintf() with the %ls format specifier does not do the job
then I would do all the output using wide characters and wcout or
wprintf(). Normally you wouldn't need to worry about whether the
underlying wide character codeset is UTF-16 or UCS-4/UTF-32.  The
compiler and underlying library should sort it out for the system for
which it is doing the compiling and run the program.  wcout << L"Hello"
should just work.

If nothing else is sufficiently portable then the best thing is to test
for the OS at compile time and code appropriately.  Glib provides the
G_OS_WIN32 and G_OS_UNIX defines which you can test for.

Chris



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]