如何将CString转换为ofstream?

kar*_*hik 1 c++

我有一些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!
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢!

Mar*_*ila 8

如果使用UNICODE,为什么不使用wofstream,这是一个使用wchar_t参数化的basic_stream.这按预期工作:

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


kar*_*hik 5

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

    ofile << CT2A(str);
Run Code Online (Sandbox Code Playgroud)

ofstream格式化的输出函数需要narrow/ansi字符串.

CStrings代表TCHAR字符串.

CT2A宏转换TCHAR 2 Ansi.

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