This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Unicode string
- From: Axel Freyn <axel-freyn at gmx dot de>
- To: eric <fsshl at att dot net>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Sun, 26 Jun 2011 16:52:42 +0200
- Subject: Re: Unicode string
- References: <1309097754.4719.6.camel@eric-laptop>
Hi Eric,
On Sun, Jun 26, 2011 at 07:15:54AM -0700, eric wrote:
> Dear c/g++ advanced programers:
> I copied and tried to test a piece simple code which is used for
> (Hardcoding a Unicode String) from the book (
> C++ Cookbook) by D. Ryan Stephens, Christopher Diggins, Jonathan
> Turkanis, and Jeff Cogswell
> at Chapter 13, Internationalization, section 1: Hardcoding a Unicode
> String
> example 13-1, it can compile and run on my g++4.5.2, but I don't quite
> satisfy its result
>
> --------------------
> //Example 13-1 Hardcoding a Unicode string
> #include <iostream>
> #include <fstream>
> #include <string>
>
> using namespace std;
>
> int main() {
>
> // Create some strings with Unicode characters
> wstring ws1 = L"Infinity: \u221E";
> wstring ws2 = L"Euro: \u0128";
>
> wchar_t w[] = L"Infinity: \u221E";
>
> wofstream out("tmp\\unicode.txt");
> out << ws2 << endl;
> wcout << ws2 << endl;
> }
As far as I know, you should absolutely NOT use non-ascii characters in
input/output operations without explicitely specifying the
encoding/localization to be used.
In your example, I would thus propose to add after the "wofstream
out..." a line like
out.imbue(locale("de_DE.UTF-8"));
which defines the encoding.
The following works for me:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
wstring ws2 = L"Euro:\x20ac";
wofstream out("unicode.txt");
out.imbue(locale("de_DE.UTF-8"));
out << ws2<< endl;
}
(besides, the Euro-symbol in Unicode is \x20ac)
In addition, you SHOULD add error-checking to your code. If you add
if(not out.good())
cerr << "Error while writing " << endl;
AFTER the line which writes into the file, you'll get an error message ....
HTH,
Axel