I have the following piece of code in C++:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
wstring ws1 = L"Infinity: \u2210";
wstring ws2 = L"Euro: €";
wchar_t w[] = L"Sterling Pound: £";
wfstream out("/tmp/unicode.txt");
out.write(ws1.c_str(), ws1.size());
out << ws1 << endl << ws2 << endl << w << endl;
out.flush();
out.close();
}
The program compiles without problem but the file is never open let alone writen on. Moreover, if I use std::wcout I still don’t get the right output, just ? for the infinity and pound symbols.
My system is g++ 4.4.3 running an ubuntu linux 10.4 64bits.
Always set the locale first… do
locale::global( locale( "" ) );. Before that, you’re in plain C mode which knows nothing about UTF-8.On Darwin, this is broken, so I need to do
setlocale( LC_ALL, "" );, but then your program works for me.Edit
Oops, you got bit by two gotchas at once. Opening a
wfstreamwith the default openmode does not create the file. I inadvertently fixed this towofstreambefore running your program, and then forgot I did. Sorry. So:or