Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to write a std::wstring into wofstream

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;
}
like image 999
sorush-r Avatar asked Feb 24 '11 11:02

sorush-r


1 Answers

Add

#include <locale>

and at the start of main,

std::locale::global(std::locale(""));
like image 80
AProgrammer Avatar answered Oct 20 '22 16:10

AProgrammer