Unable to write a std::wstring into wofstream

2019-01-26 21:24发布

问题:

I'm using Qt/C++ on a Linux system. I need to convert a QLineEdit's text to std::wstring and write it into a std::wofstream. It works correctly for ascii strings, but when I enter any other character (Arabic or Uzbek) there is nothing written in the file. (size of file is 0 bytes).

this is my code:

wofstream customersFile;
customersFile.open("./customers.txt");
std::wstring ws = lne_address_customer->text().toStdWString();
customersFile << ws << ws.length() << std::endl;

Output for John Smith entered in the line edit is John Smith10. but for unicode strings, nothing.

First I thought that is a problem with QString::toStdWString(), but customersFile << ws.length(); writes correct length of all strings. So I guess I'm doing something wrong wrong with writing wstring in file. [?]

EDIT:

I write it again in eclipse. and compiled it with g++4.5. result is same:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
   cout << "" << endl; // prints
   wstring ws = L"سلام"; // this is an Arabic "Hello"
   wofstream wf("new.txt");
   if (!wf.bad())
      wf << ws;
   else
      cerr << "some problem";
   return 0;
}

回答1:

Add

#include <locale>

and at the start of main,

std::locale::global(std::locale(""));