2011-04-05 84 views
1

我有几个CString变量,我想输出到一个ofstream,但我似乎无法弄清楚如何做到这一点。这是一些示例代码。如何将CString转换为ofstream?

我在VS支持Unicode 2005

CODE:

ofstream ofile; 
    CString str = "some text"; 

    ofile.open(filepath); 
    ofile << str; // doesn't work, gives me some hex value such as 00C8F1D8 instead 
    ofile << str.GetBuffer(str.GetLength()) << endl; // same as above 
    ofile << (LPCTSTR)str << endl; // same as above 

    // try copying CString to char array 
    char strary[64]; 
    wcscpy_s(strary, str.GetBuffer()); // strary contents are correctly copied 
    ofile << strary << endl ; // same hex value problem again! 

任何想法?谢谢!

+0

如果您使用UNICODE,那么strary应该是wchar_t而不是char。 – 2011-04-05 11:21:56

回答

5

如果你只是想简单的ACP ANSI编码的文字:

ofile << CT2A(str); 

ofstream的格式化输出函数预计狭窄/ ANSI字符串。

CStrings表示TCHAR字符串。

CT2A宏转换TCHAR 2 Ansi。

http://msdn.microsoft.com/en-us/libr...8VS.80%29.aspx

+0

尝试这与wofstream工作,我得到了“?????????(????????)”为“български” – sergiol 2016-12-06 14:35:47

+0

顺便说一句链接已死亡。 – sergiol 2016-12-06 14:36:18

8

如果使用UNICODE,你为什么不使用wofstream,这与wchar_t的参数化一个basic_stream。这符合预期:

CString str = _T("some text"); 
    std::wofstream file; 
    file.open(_T("demo.txt")); 
    file << (LPCTSTR)str; 
+0

+1 - 铸造到LPCTSTR为我做了诡计,谢谢! – 2012-05-05 18:15:01

+0

我有这样的代码;它适用于英语/拉丁语言,但不适用于保加利亚语/ CJK! :( – sergiol 2016-12-06 12:35:57

+0

我的问题已被解决,我的评论http://stackoverflow.com/a/859841/383779 – sergiol 2016-12-06 16:32:52