如何将CString转换为ofstream

How to convert CString to ofstream?

本文关键字:ofstream 转换 CString      更新时间:2023-10-16

我有一些CString变量,我希望输出到ofstream,但我似乎无法弄清楚如何做到这一点。下面是一些示例代码:

我在VS 2005中启用了unicode

代码:

  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!

任何想法?谢谢!

如果使用UNICODE,为什么不使用wofstream,它是一个由wchar_t参数化的basic_stream。如下图所示:

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

如果您只想要纯ACP编码的ANSI文本:

    ofile << CT2A(str);

ofstream格式输出函数期望窄/ansi字符串。

cstring表示char字符串

CT2A宏转换TCHAR 2 Ansi.

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