2011-04-05 60 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