6

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;
}
ST3
  • 8,826
  • 3
  • 68
  • 92
sorush-r
  • 10,490
  • 17
  • 89
  • 173
  • @Sorush Rabiee, could you please add std::endl at end of last line: `customersFile << ws << ws.length() << std::endl` just to ensure that flush has been done – Dewfy Feb 24 '11 at 12:00
  • @Dewfy: Ok but nothing is changed... – sorush-r Feb 24 '11 at 12:04
  • 1
    What are the status flags on customersFile? Is customersFile imbued with a locale supporting unicode? – AProgrammer Feb 24 '11 at 12:22
  • @AProgrammer: How do i check flags? I just checked if file `is_opened()` or not. – sorush-r Feb 24 '11 at 12:25
  • @Sorush, rdstate(), fail(), bad(), eof()... they should indicates you if there was an error. If it is the case, the root cause is probably having not set the locale correctly. – AProgrammer Feb 24 '11 at 12:32
  • @AProgrammer: All of them are false. – sorush-r Feb 24 '11 at 12:38
  • @Sorush, See if you can write a simple (without QT) standalone program reproducing the problem. If so, post it here. – AProgrammer Feb 24 '11 at 13:02
  • 2
    @AProgrammer: I added Qt-less code. Anything changed.... I'm really confused. if I can't use `wofstream` with unicode, why it exist? :-( – sorush-r Feb 24 '11 at 13:16

1 Answers1

16

Add

#include <locale>

and at the start of main,

std::locale::global(std::locale(""));
orlp
  • 112,504
  • 36
  • 218
  • 315
AProgrammer
  • 51,233
  • 8
  • 91
  • 143
  • 1
    as explained [here](http://stackoverflow.com/questions/1509277/why-does-wide-file-stream-in-c-narrow-written-data-by-default?rq=1) this is 'environment determined locale'. A somewhat more generic solution [here](http://stackoverflow.com/questions/9859020/windows-unicode-c-stream-output-failure/9869272#9869272) – mzzzzb Jul 31 '14 at 16:52