954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Unicode problem

Here I have a small piece of code:

ofstream hello ("hello.txt");
hello << "Γειά σου!"; //hello in greek
hello.close();


And here is the output:

Output on greek windows: "Γειά σου!"
Output on english windows: "ÃåéÜ óïõ!"


Can someone, please, help me find out how to fix this?

SpecialForce
Newbie Poster
20 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

You might find this interesting : http://mariusbancila.ro/blog/2008/10/20/writing-utf-8-files-in-c/

The example gives a solution for windows, but you could find some other articles explaining how to make the translation to UTF-8.

akhena
Light Poster
32 posts since Jan 2011
Reputation Points: 29
Solved Threads: 5
 

Thanks a lot akhena, I found the solution, using what this page uses plus locale! Here is the complete source code:

#include "stdafx.h"
#include <windows.h>
#include <fstream>
#include <string>
#include <locale>
#pragma setlocale("Greek")
using namespace std;

string to_utf8(const wchar_t* buffer, int len)
{
        int nChars = ::WideCharToMultiByte(
                CP_UTF8,
                0,
                buffer,
                len,
                NULL,
                0,
                NULL,
                NULL);
        if (nChars == 0) return "";

        string newbuffer;
        newbuffer.resize(nChars) ;
        ::WideCharToMultiByte(
                CP_UTF8,
                0,
                buffer,
                len,
                const_cast< char* >(newbuffer.c_str()),
                nChars,
                NULL,
                NULL); 

        return newbuffer;
}

string to_utf8(const std::wstring& str)
{
        return to_utf8(str.c_str(), (int)str.size());
}

int main()
{
        ofstream testFile;

        testFile.open("demo.txt", ios::out | ios::binary); 

        wstring text =
                L"Γειά σου!";

        string outtext = to_utf8(text);

        testFile << outtext;

        testFile.close();

        return 0;
}


Thanks a lot again!

SpecialForce
Newbie Poster
20 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

Glad I could help. :)

akhena
Light Poster
32 posts since Jan 2011
Reputation Points: 29
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You