Writing to wofstream throws an exception

I am trying to just write the wchar_t * file to a file, but the command line output of the compiled program is given below. In fact, the program freezes when trying to write a Greek string.

el_GR.UTF-8
terminate called after throwing an instance of 'int'
Ακυρώθηκε (core dumped)

Source code below

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <wchar.h>
using namespace std;

int main(int argc, char **argv)
{

    printf("%s\n",setlocale(LC_ALL,""));
    wofstream f("xxx.txt", ios::out);
    if(f.is_open())
    {
        try
        {
            f.write(L"good",4);
            f.flush();
            f.write(L"καλημερα",8);
            f.close();
        }
        catch (int e)
        {
            cout << "An exception occurred. Exception Nr. " << e <<endl;
        }

        printf("hello world\n");
        return 0;
    }
}

Why?

+4
source share
1 answer

The stream does not take the locale from the medium. I added:

#include <locale>
locale loc("el_GR.utf8");
f.imbue(loc);

So, the stream now supports the locale (if I'm wrong, please correct).

The correct code is:

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <wchar.h>
#include <locale>


using namespace std;

int main(int argc, char **argv)
{
    locale loc("el_GR.utf8");
    wcout<<"Hi I am starting Ξεκινάμε"<<endl;
    cout<<"%s\n"<<setlocale(LC_ALL,"en_US.utf8")<<endl;
    wofstream f("xxx.txt", ios::out);
        if(f.is_open()){
            f.imbue(loc);

            f.write(L"good",4);f.flush();
            f.write(L"καλημέρα",8);
            f.close();
            cout<<"fileClosed"<<endl;
  }

    cout<<"hello world"<<endl;
    return 0;


}
+1
source

All Articles