1

I have a few CString variables that I wish to output to an ofstream, but I can't seem to figure out how to do so. Here's some example code.

I have unicode enabled in VS 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!

Any ideas? Thanks!

tenfour
  • 36,141
  • 15
  • 83
  • 142
karthik
  • 17,453
  • 70
  • 78
  • 122

2 Answers2

9

If using UNICODE, why don't you use wofstream, which is a basic_stream parametrized with wchar_t. This works as expected:

  CString str = _T("some text");
  std::wofstream file;
  file.open(_T("demo.txt"));
  file << (LPCTSTR)str;
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • I had my code like this; it works well with English/Latin languages, but not with Bulgarian/CJK ! :( – sergiol Dec 06 '16 at 12:35
  • My problem has been solved as reported in my comment on http://stackoverflow.com/a/859841/383779 – sergiol Dec 06 '16 at 16:32
5

If you just want plain ACP encoded ANSI text:

    ofile << CT2A(str);

ofstream formatted output functions expect narrow/ansi strings.

CStrings represent TCHAR strings.

The CT2A macro Converts TCHAR 2 Ansi.

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

karthik
  • 17,453
  • 70
  • 78
  • 122