This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: can't write wide character/string to outputfile
Hi,
>
>
> I have slightly modified the program
>
> #include <iostream>
> #include <fstream>
> #include <string>
> using namespace std;
> int main() {
> wstring ws2 = L"Euro:\x20ac";
> wofstream out("unicode.txt");
> // out.imbue(locale("el_GR.UTF-8"));
> out << ws2<< endl;
> wcout << ws2;
> }
>
> and this prints the word Euro on the terminal while the
> output file is still empty.
>
Well, I'm not an expert in localization, however I would propose you try
a code like the following:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
wstring ws2 = L"Euro: \x20ac";
wofstream out("unicode.txt");
if(not out.good())
cerr << "Error opening output file" << endl;
const char *name = "el_GR.UTF-8";
if(argc == 2)
name = argv[1];
cout << "trying to access locale " << name << endl;
locale loc;
try{
loc = locale(name);
cout << "Generated locale " << loc.name() << endl;
}catch( exception &e){
cerr << "Couldn't generate locale " << name << ": " << e.what() << endl;
}
out.imbue(loc);
if(not out.good())
cerr << "Error when setting the locale" << endl;
out << ws2<< endl;
if(not out.good())
cerr << "Error when writing to file" << endl;
}
It has much more error-checking integrated, such that I would hope we
get a clear answer where the error happens. My code takes 1 command-line
parameter, which it interpretes as the desired locale.
I expect the following behaviour (let's call the compiled program "test":
- if you start it as "./test C" or "./test POSIX", it should succeed to
generate those locales (they are defined by the C++-Standard), but
fail in the last line when trying to write the Euro-symbol into the
file.
- if you start it was an utf-8--encoding, (like el_GR.UTF-8),
everything should run fine IF this encoding exists on your machine.
However, the C++-standard says that the encodings are implementation
defined, and the gcc-documentation says it's up to glibc:
http://gcc.gnu.org/onlinedocs/gcc/Locale_002dspecific-behavior-implementation.html
On my machine, the names are case-sensitive -- so maybe you should
try some other spellings like el_GR.utf-8 or el_GR.utf8 or ...?
Axel