Unable to write a std::wstring into wofstream

谁都会走 提交于 2019-11-28 04:51:59

问题


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(""));


来源:https://stackoverflow.com/questions/5104329/unable-to-write-a-stdwstring-into-wofstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!