Search code examples
c++stlc++buildervcl

ofstream output of std::map<UnicodeString, UnicodeString> yields addresses not strings


I have a stl map container filled with pairs of vcl UnicodeString objects. I'm trying to dump it to file with the code quoted below but instead of my strings I'm getting a file full of hex addresses.

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <map>

//---------------------------------------------------------------------------
WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
      std::map<UnicodeString, UnicodeString> fm;
      fm[U"a"]=U"test";
      fm[U"b"]=U"test2";
      fm[U"c"]=U"test3";
      fm[U"z"]=U"last one";
      ofstream out("c:\\temp\\fm.txt");
      std::map<UnicodeString, UnicodeString>::const_iterator itr;
      for (itr = fm.begin(); itr != fm.end(); ++itr) {
          out << itr->first.c_str()<< ",\t\t"<< itr->second.c_str()<<std::endl;
      }

      out.close();

   return 0;
}

yields this:

1f3b624,                1f5137c
1f3b654,                1f513bc
1f3b66c,                1f513fc
1f3b684,                1f258dc

I've tried various ways of casting the c string but nothing seems to work.


Solution

  • As usual the answer is quite straightforward, I was lead to it by @Dauphic's comment. I was using a 'narrow stream'. The solution is to use a wide stream, which I was surprised to discover exists!

    The solution is to change the stream declaration to:

    std::wofstream out("c:\\temp\\fm.txt");
    

    and presto changeo it works.

    The solution is also found here