Question

The reference http://www.fileformat.info/info/unicode/char/2192/index.htm says that right arrow is 0x2192 in unicode character set, so I try to write the value to a file in a couple of different ways:

#include <fstream>

using namespace std;

int main()
{
    ofstream out("out.txt");
    wofstream wout("wout.txt");

    out << '0x2192' << endl;
    out << '\u2192' << endl;
    out << L'\u2192' << endl;
    out << u'\u2192' << endl;

    wout << '0x2192' << endl;
    wout << '\u2192' << endl;
    wout << L'\u2192' << endl;
    wout << u'\u2192' << endl;

    return 0;
}

It just prints out numbers and no arrow symbol. What am I doing wrong? PS Also I want to read back the character later. Thanks in advance.

Was it helpful?

Solution

With some modifications:

#include <fstream>
#include <locale>

using namespace std;

int main() {
    // This is the real trick, make the wfostream to print wide characters as
    // UTF-8
    // what we're going to do is to create a locale that has the ctype category
    // copied from the "en_US.UTF-8"
    std::locale loc=std::locale(std::locale(),"en_US.UTF8",std::locale::ctype);
    ofstream out("out.txt");
    // and now add the locale to the stream
    out.imbue(loc);
    wofstream wout("wout.txt");
    // and now add the locale to the stream
    wout.imbue(loc);

    //out << '0x2192' << endl;           // character constant too long (did not compile on g++)
    //out << '\u2192' << endl;           // character constant too long (did not compile on g++)
    out << L'\u2192' << endl;            // prints 8594
    out << u'\u2192' << endl;            // prints 8594
    out << (wchar_t) L'\u2192' << endl;  // prints 8594
    out << (wchar_t) u'\u2192' << endl;  // prints 8594

    //wout << '0x2192' << endl;          // character constant too long
    //wout << '\u2192' << endl;          // character constant too long
    wout << 8594 << endl;                // prints 8594
    wout << L'\u2192' << endl;           // prints ->
    wout << u'\u2192' << endl;           // prints 8594
    wout << (wchar_t) 8594 << endl;      // prints ->
    wout << (wchar_t) L'\u2192' << endl; // prints ->
    wout << (wchar_t) u'\u2192' << endl; // prints ->    
    return 0;
}

the above was executed on Ubuntu linux and compiled with g++

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top