【问题标题】:How to convert CString to ofstream?如何将 CString 转换为 ofstream?
【发布时间】:2011-07-29 21:08:02
【问题描述】:

我有一些 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 那么 strary 应该是 wchar_t 而不是 char。

标签: c++


【解决方案1】:

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

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

【讨论】:

  • 我的代码是这样的;它适用于英语/拉丁语,但不适用于保加利亚语/CJK! :(
  • 我的问题已经解决,正如我对stackoverflow.com/a/859841/383779的评论中所报告的那样
【解决方案2】:

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

    ofile << CT2A(str);

ofstream 格式的输出函数需要窄/ansi 字符串。

CStrings 代表 TCHAR 字符串。

CT2A 宏转换 TCHAR 2 Ansi。

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

【讨论】:

  • 尝试与 wofstream 一起工作,我得到了“български”的“????????? (??????????)”
  • BTW 链接已失效。
猜你喜欢
  • 2023-04-01
  • 2011-11-23
  • 2012-03-07
  • 2014-11-27
  • 2011-04-30
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多