2011-02-24 117 views
3

我在Linux系统上使用Qt/C++。我需要将QLineEdit的文本转换为std::wstring并将其写入std::wofstream。它对ascii字符串正常工作,但是当我输入任何其他字符(阿拉伯语或乌兹别克语)时,文件中没有写入任何内容。 (文件的大小是0字节)。无法在wofstream中写入std :: wstring

这是我的代码:

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

输出为行编辑进入John SmithJohn Smith10。但对于unicode字符串,什么都没有。

首先,我认为这是QString::toStdWString()的问题,但customersFile << ws.length();写入所有字符串的正确长度。所以我想我在写文件wstring时做错了什么。 [?]

编辑:

我在eclipse中再次写它。并用g ++ 4.5编译它。结果是一样的:

#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; 
} 
+0

@Sorush Rabiee,请您在最后一行的末尾添加的std :: ENDL: 'customersFile << ws << ws.length()<< std :: endl'只是为了确保刷新已完成 – Dewfy 2011-02-24 12:00:34

+0

@Dewfy:好的,但没有任何更改... – 2011-02-24 12:04:11

+1

customersFile上的状态标志是什么? customersFile充满了支持unicode的语言环境吗? – AProgrammer 2011-02-24 12:22:53

回答

13

添加

#include <locale> 

,并在主要的开始,

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

as described [here](http://stackoverflow.com/questions/1509277/why-does-wide-file-stream-in-c-narrow-written-data-by-default?rq=1)这是'环境确定区域设置'。一个更通用的解决方案[这里](http://stackoverflow.com/questions/9859020/windows-unicode-c-stream-output-failure/9869272#9869272) – mzzzzb 2014-07-31 16:52:43