Why does the following code create an empty file? I am using Windows
XP.
#include <iostream>
#include <fstream>
int main()
{
std::wofstream fout("data.txt");
This creates a stream using the current default locale. Since
you haven't set the locale, you get the "C" locale.
if( fout )
{
fout << L"\u2620\u262D\u262F" << std::endl;
And there's no such character as "\u2620" in the "C" locale, so
conversion fails, which causes the output to fail, which means
that no further output can occur until you clear() the error
status.
Unless you are restricting your characters to US ASCII (and
if so, why bother with wofstream), you're main() should almost
always start:
std::locale::global( std::locale( "" ) ) ;
std::wcout.imbue( std::locale() ) ;
std::wcin.imbue( std::locale() ) ;
std::wcerr.imbue( std::locale() ) ;
Otherwise, it is probable that trying to output any character
not in the basic execution character set may fail. (Actually,
most implementations allow a few additional characters, such as
'$' or '@'. But this is not guaranteed. Of course, nothing you
do with the locales is really guaranteed either. If the user is
in a locale where there is no character "\u2620"---which would
be my case, for example---then you'll still end up with an
error. And to refer vaguely to another thread here: if the user
has selects a font with a different encoding than that of the
locale when he views the file, who knows what he'll get. But
the lines above make it the user's problem, and not yours
.)